I have an asp.net web forms application running under v4.0 integrated mode.
I tried to add an apicontroller in the App_Code folder.
In the Global.asax, I added the following code
RouteTable.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } );
When I tried to navigate to the controller at http://localhost/api/Value
, I get the 404 error.
The extensionless url is configured in the handler section. I have forms and anonymous authentication enabled for the website.
ExtensionLess url is configured for '*.'
When I hit the url for controller, the request is handled by StaticHandler instead of ExtensionlessUrlHandler-Integrated-4.0.
I have no clue now why the system will throw the error as shown in the image below.
A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.
Fortunately you don't need to parse the customErrors section to get name of the custom 404 page. Just throw HttpException: throw new HttpException(404, "Page you requested is not found"); ASP.NET run-time will catch the exception and will redirect to the custom 404.
I was experiencing this problem.
I tried editing my WebApiConfig.cs
to meet a number of recommendations here and code samples elsewhere. Some worked, but it didn't explain to why the route was not working when WebApiConfig.cs
was coded exactly as per the MS template WebApi project.
My actual problem was that in manually adding WebApi
to my project, I had not followed the stock order of configuration calls from Global.asax
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); // This is where it "should" be GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); // The WebApi routes cannot be initialized here. BundleConfig.RegisterBundles(BundleTable.Bundles); }
I could make guesses about why this is, but I didn't investigate further. It wasn't intuitive to say the least.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With