Programing

모든 ASP.NET Web API 컨트롤러가 404를 반환합니다.

crosscheck 2020. 12. 10. 18:52
반응형

모든 ASP.NET Web API 컨트롤러가 404를 반환합니다.


ASP.NET MVC 4 웹 앱 내에서 작동하도록 API 컨트롤러를 얻으려고합니다. 그러나 모든 요청은 404를 발생 시키고 난처합니다. : /

다음과 같이 정의 된 프로젝트 템플릿의 표준 API 컨트롤러 경로가 있습니다.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

등록은 Global.asax에서 호출됩니다.

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register API routes
    WebApiConfig.Register(GlobalConfiguration.Configuration);

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
}

다음과 같은 기본 API 컨트롤러가 있습니다.

namespace Website.Controllers
{
    public class FavoritesController : ApiController
    {       
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new [] { "first", "second" };
        }

        // PUT api/<controller>/5
        public void Put(int id)
        {

        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {

        }
    }
}

이제 localhost : 59900 / api / Favorites를 탐색 할 때 Get 메서드가 호출 될 것으로 예상 하지만 대신 404 상태 코드와 다음 응답을 받습니다 .

<Error>
   <Message>
       No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
   </Message>
   <MessageDetail>
      No type was found that matches the controller named 'Favorites'.
   </MessageDetail>
</Error>

어떤 도움이라도 대단히 감사하겠습니다. 나는 여기에서 약간의 정신을 잃고 있습니다. :) 감사!


내가 만난 한 가지는 예를 들어 GLobal.asax 파일에 잘못된 순서로 구성을 등록하는 것입니다.

올바른 순서:

AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);

잘못된 주문 :

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);

그냥 내 문제 였고 순서를 바꾸는 건 당연하지만 가끔 간과되어 많은 좌절감을 줄 수 있습니다.


본질적으로 동일한 문제가 있었고 내 경우에는 다음을 추가하여 해결했습니다.

<modules runAllManagedModulesForAllRequests="true" />

~로

<system.webServer>

</system.webServer>

web.config 섹션


나는 이와 비슷한 문제를 연구 해 왔으며 문제를 찾는 데 오랜 시간이 걸렸습니다. 이 특정 게시물에 대한 해결책은 아니지만 이것을 추가하면 컨트롤러에 대해 404 오류가 발생할 수있는 이유를 검색 할 때 문제를 찾는 데 시간을 절약 할 수 있습니다.

기본적으로 클래스 이름 끝에 "Controller"철자를 잘못 입력했습니다. 그렇게 간단합니다!


다음 줄 추가

GlobalConfiguration.Configure(WebApiConfig.Register);

에서 Application_Start()의 기능 Global.ascx.cs의 파일.


I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.


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


Similar problem with an embarrassingly simple solution - make sure your API methods are public. Leaving off any method access modifier will return an HTTP 404 too.

Will return 404:

List<CustomerInvitation> GetInvitations(){

Will execute as expected:

public List<CustomerInvitation> GetInvitations(){

I'm a bit stumped, not sure if this was due to an HTTP output caching issue.

Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.

Guess the code just had to sit and cook overnight... :)

Thanks for helping, guys!


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.


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);
}

I'm going to add my solution here because I personally hate the ones which edit the web.config without explaining what is going on.

For me it was how the default Handler Mappings are set in IIS. To check this...

  1. Open IIS Manager
  2. Click on the root node of your server (usually the name of the server)
  3. Open "Handler Mappings"
  4. Under Actions in the right pane, click "View ordered list"

This is the order of handlers that process a request. If yours are like mine, the "ExtensionlessUrlHandler-*" handlers are all below the StaticFile handler. Well that isn't going to work because the StaticFile handler has a wildcard of * and will return a 404 before even getting to an extensionless controller.

So rearranging this and moving the "ExtensionlessUrlHandler-*" above the wildcard handlers of TRACE, OPTIONS and StaticFile will then have the Extensionless handler activated first and should allow your controllers, in any website running in the system, to respond correctly.

Note: This is basically what happens when you remove and add the modules in the web.config but a single place to solve it for everything. And it doesn't require extra code!


Add this to <system.webServer> in your web.config:

<handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="OPTIONSVerbHandler"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
        preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>

Adding <modules runAllManagedModulesForAllRequests="true" /> also works but is not recommended due performance issues.


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.


I had the same 404 issue and none of the up-voted solutions here worked. In my case I have a sub application with its own web.config and I had a clear tag inside the parent's httpModules web.config section. In IIS all of the parent's web.config settings applies to sub application.

<system.web>    
  <httpModules>
    <clear/>
  </httpModules>
</system.web>

The solution is to remove the 'clear' tag and possibly add inheritInChildApplications="false" in the parent's web.config. The inheritInChildApplications is for IIS to not apply the config settings to the sub application.

<location path="." inheritInChildApplications="false">
  <system.web>
  ....
  <system.web>
</location>

WebApiConfig.Register(GlobalConfiguration.Configuration);

Should be first in App_start event. I have tried it at last position in APP_start event, but that did not work.


Had this problem. Had to uncheck Precompile during publishing.

참고URL : https://stackoverflow.com/questions/15556035/all-asp-net-web-api-controllers-return-404

반응형