All ASP.NET Web API controllers return 404

前端 未结 19 1644
臣服心动
臣服心动 2020-12-08 01:48

I\'m trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404 and I\'m stumped. :/

I have th

相关标签:
19条回答
  • 2020-12-08 02:15

    Create a Route attribute for your method.

    example

            [Route("api/Get")]
            public IEnumerable<string> Get()
            {
                return new string[] { "value1", "value2" };
            }
    

    You can call like these http://localhost/api/Get

    0 讨论(0)
  • 2020-12-08 02:16

    I had this problem: My Web API 2 project on .NET 4.7.2 was working as expected, then I changed the project properties to use a Specific Page path under the Web tab. When I ran it every time since, it was giving me a 404 error - it didn't even hit the controller.

    Solution: I found the .vs hidden folder in my parent directory of my VS solution file (sometimes the same directory), and deleted it. When I opened my VS solution once more, cleaned it, and rebuilt it with the Rebuild option, it ran again. There was a problem with the cached files created by Visual Studio. When these were deleted, and the solution was rebuilt, the files were recreated.

    0 讨论(0)
  • 2020-12-08 02:18

    I have solved similar problem by attaching with debugger to application init. Just start webserver (for example, access localhost), attach to w3wp and see, if app initialization finished correctly. In my case there was exception, and controllers was not registered.

    0 讨论(0)
  • 2020-12-08 02:19

    For reasons that aren't clear to me I had declared all of my Methods / Actions as static - apparently if you do this it doesn't work. So just drop the static off

    [AllowAnonymous]
    [Route()]
    public static HttpResponseMessage Get()
    {
        return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    }
    

    Became:-

    [AllowAnonymous]
    [Route()]
    public HttpResponseMessage Get()
    {
        return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
    }
    
    0 讨论(0)
  • 2020-12-08 02:22

    Add following line

    GlobalConfiguration.Configure(WebApiConfig.Register);
    

    in Application_Start() function in Global.ascx.cs file.

    0 讨论(0)
  • 2020-12-08 02:23

    Check that if your controller class has the [RoutePrefix("somepath")] attribute, that all controller methods also have a [Route()] attribute set.

    I've run into this issue as well and was scratching my head for some time.

    0 讨论(0)
提交回复
热议问题