Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

c# - ASP.NET MVC WebAPI 404 error

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. Error

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...