HTTP Error 400.0 - Bad Request When using special character in asp.net 3.5 routing - webforms

I have an .net framework 3.5 website in which I routed a path.
site.com/mypath/text goes to site.com/webpage/ and the webpage gets the text.
This occurs when the text contains asterisk(*) or colon(:)
It's not an encoding problem * or %2A yelds the same result.
Most fixes for this problem are for framework 4 and above and I cannot upgrade.
The code I use:
private void RegisterRoutes(RouteCollection routes)
{
CustomRouteHandler x = new CustomRouteHandler("~/page.aspx");
routes.Add("mypath",new Route("mypath/{text}", x));
}

Related

An API version is required, but was not specified. webapi

var constraintResolver = new DefaultInlineConstraintResolver()
{
ConstraintMap =
{
["apiVersion"] = typeof( ApiVersionRouteConstraint )
}
};
config.MapHttpAttributeRoutes(constraintResolver);
config.AddApiVersioning(o => o.AssumeDefaultVersionWhenUnspecified = true);
[ApiVersion("2.05")]
[RoutePrefix("api/v{version:apiVersion}/ger")]
public class caGerController
[Route("~/api/ger/getDetail")]
[Route("getDetail")]
GetGerData
[ApiVersion("1")]
[RoutePrefix("api/v{version:apiVersion}/gerDetail")]
public class caGerDetailsController
caGerController
[Route("~/api/gerDetail/getDetail")]
[Route("getDetail")]
GetGerData
>> GetGerData
Result:
Both URL working with v1 version ROUTE.
Second URL working for both, v1 and direct without v1 route as well i.e. [Route("~/api/gerDetail/getDetail")]
PROBLEM: first URL is only working with v1 and its not working with direct route like " [Route("~/api/ger/getDetail")]"
and getting an error as below:
"Error": {
"Code": "ApiVersionUnspecified",
"Message": "An API version is required, but was not specified."
}
How to solve this issue?
When I change from 2.05 to 1.0 then it works but 2.0 or 2.05 both do not work. Is there a separate folder required?
The ApiVersionUnspecified happens because all routes require an explicit API version by default. You opt out of this behavior using:
options.AssumeDefaultVersionWhenUnspecified = true
This setting means that a default API version is assumed when a client doesn't provide one. The default value is:
options.DefaultApiVersion // equals 1.0 by default
When you use the URL segment versioning method, you can't have two different controllers that both an unversioned route. The route without an API version can only map to a single controller. Since the default is "1.0" and you have a controller with the unversioned route, that's the one that will always been matched.
By adding API versioning, the default behavior is that it uses QueryString versioning.
config.AddApiVersioning(cfg => {});
api-version=1.0
To specify a version, you can add the querystring parameter api-version=1.0 at the end.
Example:
http://localhost:6600/api/test?api-version=1.0
You can change the version like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
...
public static void Register(HttpConfiguration config)
{
...
config.AddApiVersioning(cfg =>
{
cfg.DefaultApiVersion = new ApiVersion(1,1);
});
So you can change the version like this:
http://localhost:6600/api/test?api-version=1.1
By adding AssumeDefaultVersionWhenUnspecified, you don't have to specify a version.
config.AddApiVersioning(cfg =>
{
cfg.DefaultApiVersion = new ApiVersion(1,1);
cfg.AssumeDefaultVersionWhenUnspecified = true;
});
This will work:
http://localhost:6600/api/test
You can also add ReportApiVersions
config.AddApiVersioning(cfg =>
{
cfg.DefaultApiVersion = new ApiVersion(1,1);
cfg.AssumeDefaultVersionWhenUnspecified = true;
cfg.ReportApiVersions = true;
});
The response will have a new header api-supported-versions which specifies what versions are supported for the call they made.

Can't get ASP.NET Web API 2 Help pages working when using Owin

I've installed the correct package for Web Api 2
Install-Package Microsoft.AspNet.WebApi.HelpPage -Pre
But the help area is not being mapped and is returning 404 (Web Api working fine). I'm using Microsoft.Owin.Host.SystemWeb as the host. Below is my Startup code.
public class Startup
{
public void Configuration(IAppBuilder app)
{
//Required for MVC areas new HttpConfiguration() doesn't work with MVC
var config = GlobalConfiguration.Configuration;
AreaRegistration.RegisterAllAreas();
WepApiStartup.Configure(config);
app.UseWebApi(config);
}
}
GlobalConfiguration.Configuration is web host specific HttpConfiguraiton, which should only be used with web host scenario. Use it with OWIN host will cause unexpected issues.
Please use the following code instead:
public class Startup
{
public static HttpConfiguration HttpConfiguration { get; private set; }
public void Configuration(IAppBuilder app)
{
HttpConfiguration = new HttpConfiguration();
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(HttpConfiguration);
app.UseWebApi(HttpConfiguration);
}
}
Replace all GlobalConfiguration.Configuration with Startup.HttpConfiguration in the project include help page files.
Found the solution after a lot of digging/trial and error. The issue is well described here: http://aspnetwebstack.codeplex.com/discussions/453068
UseWebApi and UseHttpMessageHandler don't call Next OWIN's middleware other than for 404. This means if you use UseWebApi that's it, Next is never called therefore you can't use it with any other middleware (Nancy or Web Api Help pages for example).
Thanks to #aliostad patch:
https://github.com/aliostad/CacheCow/blob/master/samples/UsingCacheCowWithNancyAndOwin/HttpMessageHandlerAdapterModified.cs#L43
You can get it working as expected. I hope the team merge the pull request for this as UseWebApi breaks the Owin design goals IMO.
Update 13 Feb 2014
I've written an Owin extension to workaround this:
internal static void UseWebApiAndHelp(this IAppBuilder app, HttpConfiguration config)
{
WepApiStartup.Configure(config);
app.UseHandlerAsync((request, response, next) =>
{
if (request.Path == "/") //app.Map using a regex exclude list would be better here so it doesn't fire for every request
{
response.StatusCode = 301;
response.SetHeader("Location", "/Help");
return Task.FromResult(0);
}
return next();
});
// Map the help path and force next to be invoked
app.Map("/help", appbuilder => appbuilder.UseHandlerAsync((request, response, next) => next()));
app.UseWebApi(config);
}
Update 01 July 2015
You can also host the help pages using WebApi instead of MVC, which is great for self host http://blogs.msdn.com/b/yaohuang1/archive/2012/12/20/making-asp-net-web-api-help-page-work-on-self-hosted-services.aspx
Update 10 September 2015
For Web Api I tried #hongye-sun answer and it works too, follow what #gspatel says by changing HelpPageAreaRegistration.RegisterArea and the HelpController's constructor. My workaround works as well so pick whatever one works best for your situation.
However I'm still getting the issue when using UseWebApi with other middleware and it not invoking Next() (seems to only happen when using IIS not self host). I've found my workaround of mapping the path and forcing next to be invoked is a valid workaround for all Owin middleware Nancy, Simple.Web etc.
Update 13 Jan 2016
I've developed Owin middleware to generate the ASP.NET Web API Help pages we know and love that completely solves this problem. My blog post explains the background to this issue in detail

Redirect permanently 301 in blogengine.net (global.asax)

i want to redirect my old address www.informarea.it/BlogEngine to new address www.informarea.it...
*my global.asax of blogengine.net is *
void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
// Attempt to perform first request initialization
FirstRequestInitialization.Initialize(context);
}
*can i make to apply the code of redirect permanently? *
if (app.url.ToString().ToLower().Contains("http://www.informarea.it/BlogEngine"))
{
HttpContext.Current.Response.Status = "301 Moved Permanently";
HttpContext.Current.Response.AddHeader("Location",url.Replace("http://www.informarea.it/blogengine", "http://www.informarea.it"));
}
Can Someone help me?
thank you very much
Fabry
This should redirect any query where the path starts with /BlogEngine to the same url with the /BlogEngine removed.
if(Request.Url.PathAndQuery.StartsWith("/BlogEngine", StringComparison.OrdinalIgnoreCase)) {
Response.RedirectPermanent(Request.Url.PathAndQuery.Substring(11), true);
}
Pros:
Gives a 301 Redirect like you requested
Keeps the rest of the path and query string intact for the following request
Cons:
Requires .net 4.0 (Version 2.7 of BlogEngine is targeted at 4.0 so I don't think this will be an issue.)

Configuring IIS 6.0 to run an MVC3 application

Configuring IIS 6.0 to run an MVC3 application
I think I have a configuration issue on my IIS 6 server and I'd like to see if there's anything I've missed.
The problem that I'm having is that anytime when a RedirectToAction("Index", "Home") is executed (e.g. in a method that returns an ActionResult) I would expect that I would be returned to:
http://servername.domain.com/virtualdirectoryname
However, instead I get redirected to:
http://servername.domain.com/virtualdirectoryname/virtualdirectoryname
That is a second instance of the virtualdirectoryname appended to the end of the URL and can't figure out why - this URL will of course yield a 404 resource not found error. I written and deployed several MVC3 applications both in corporate intranet and public internet environments and can't figure out what I've done wrong. My global.asax.cs seems ok -
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.User != null)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity is FormsIdentity)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
// Get the stored user-data, in this case, our roles
string userData = ticket.UserData;
string[] roles = userData.Split(',');
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, roles);
}
}
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
The Application_AuthenticateRequest handles the storing of the roles for logged on users, but other than that, it seems pretty vanilla. The only think I can think of is that I've somehow messed up the virtual directory.
Prior to performing any of these steps, I had verified that MVC3 and v4.0 of the .NET framework were installed on the server. There are also other ASP.NET 4.0 applications on this server that have been running without incident. There is also an MVC2 application (MVC2 is also installed) running on this server and has been running without incident.
I created a virtual directory off of the main "default site" using the IIS manager.
Setup appropriate permissions on the folder that this virtual directory points to. Tested with a quick "Hello, World" index.html file.
Copied the application from my development PC where the application works as developed to the folder described in #2.
Updated the Web.Config file, editing the connection strings to point to the test database server; I had also verified these connection strings on my development PC.
Open the web browser and hope for the best.
Any assistance is greatly appreciated.
Thanks!
I think what you may be seeing is:
http://servername.domain.com/virtualdirectoryname/applicationname
If you have named your virtual directory the same name as your application then I could see how that could confuse you. If you had no virtual directory and just your application at the root of the Default Web Site you'd be seeing:
http://servername.domain.com/applicationname
Is your virtual directory the same name as your application name? If so, that is why you see this.

asp.net mvc 3 and static resources 404'ing when using "Local IIS Web server"

Here's the situation:
ASP.NET MVC 3 application using Razor as the view engine.
Works fine under Visual Studio Development Server (Cassini)
However, when I switch over to "Use Local IIS Web server", the site functions, but every static resource 404s (again, there were no issues under Cassini).
ASP.NET 4.0, Windows 7 Ultimate x64, IIS 7.5, Integrated Pipeline, Network Service as app pool identity.
Specifically, an exception for trying to access a static file that is known to exist (i.e. remove application files, specifically DLLs with route information, etc. and it is served up without issue). Again, this occurs for all static files including i.e. /public/scripts/jquery.js:
Error in Path :/favicon.ico
Raw Url :/favicon.ico
Message :Path '/favicon.ico' was not found.
Source :System.Web
Stack Trace : at System.Web.HttpNotFoundHandler.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
TargetSite :Void ProcessRequest(System.Web.HttpContext) NLogLogger.Fatal => NLogLogger.Fatal => LoggerImpl.Write
I'm baffled. I've verified that a test default ASP.NET MVC 3 app runs fine under both VS Development Server and Local IIS Web server on this machine.
My hope is that someone else has run into a similar issue. In case it helps, here are my routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("favicon.ico");
routes.MapRoute(
"Login", // Route name
"login", // URL with parameters
new { controller = "Session", action = "Create" } // Parameter defaults
);
routes.MapRoute(
"Logout", // Route name
"logout", // URL with parameters
new { controller = "Session", action = "Delete" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Of course, it turns out to be something extremely simple: there was an HttpHandler defined in the root Web.config instead of just the View directory's Web.config
<handlers>
<remove name="BlockViewHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
Obvious now, but hopefully by posting here it might save somebody else wasting time on something so obvious. See http://haacked.com/archive/2008/06/25/aspnetmvc-block-view-access.aspx for more info.

Resources