development

WebAPI 삭제가 작동하지 않습니다-405 메소드가 허용되지 않습니다

big-blog 2020. 7. 25. 10:15
반응형

WebAPI 삭제가 작동하지 않습니다-405 메소드가 허용되지 않습니다


사이트가 오늘 밤 라이브로 이동해야하므로 이에 대한 도움을 주셔서 감사합니다!

Delete 메서드가있는 웹 API 컨트롤러가 있습니다. 이 방법은 IIS Express (Windows 8)를 실행하는 로컬 컴퓨터에서 제대로 실행되지만 실제 IIS 서버 (Windows Server 2008 R2)에 배포하자마자 작동이 중지되고 다음 오류 메시지가 표시됩니다.

HTTP 오류 405.0-허용되지 않는 메소드 유효하지 않은 메소드 (HTTP 동사)를 사용 중이므로 찾고있는 페이지를 표시 할 수 없습니다.

웹을 둘러보고 솔루션을 찾고 가장 합리적인 솔루션을 구현했습니다. 내 웹 구성에는 다음 설정이 있습니다.

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
<handlers>
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
    <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

또한 IIS의 처리기 매핑 및 요청 필터링을 사용할 수 없도록 변경하려고했습니다. IIS의 WebDAV 작성 규칙이 비활성화 된 것 같습니다.

어떤 아이디어라도 대단히 감사하겠습니다 감사합니다.


결국 해결책을 찾았습니다! 같은 문제가 발생하면 web.config에 다음을 추가하십시오.

<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- ADD THIS -->
    </modules>
    ... rest of settings here

이게 도움이 되길 바란다


경우에 따라 모듈에서 모듈을 제거하면 다음 오류가 발생할 수 있습니다.

500.21 처리기 "WebDAV"의 모듈 목록에 잘못된 "WebDAVModule"모듈이 있습니다.

모듈 : IIS 웹 코어 알림 : ExecuteRequestHandler "

해결책이 여기 에 제안 되었습니다 . 또한 핸들러에서 제거해야합니다.

<system.webServer>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
    <handlers>
        <remove name="WebDAV" />
    </handlers>
</system.webServer>

제 경우에는 위의 해결책 중 어느 것도 작동하지 않았습니다. 내가했던 때문이었다 매개 변수의 이름을 변경 내에서 Delete방법.

나는했다

public void Delete(string Questionid)

대신에

public void Delete(string id)

파일에 id선언 된 이름이므로 이름 을 사용해야 WebApiConfig합니다. id세 번째와 네 번째 줄 이름을 참고하십시오 .

            config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

I got this solution from here.


The Javascript for HTTP DELETE verb must be like this:

$.ajax({
    **url: "/api/SomeController/" + id,**
    type: "DELETE",
    dataType: "json",
    success: function(data, statusText) {
        alert(data);
    },
    error: function(request, textStatus, error) {
        alert(error);
        debugger;
    }
});

Do not use something like this:

...
data: {id:id}
...

as when you use the POST method.


After trying almost every solutions here this worked for me. Add this in your APIs config file

<system.webServer>
    <handlers>
      <remove name="WebDAV" />
      <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>
    <modules>
        <remove name="WebDAVModule" />
    </modules>
</system.webServer>

I also had the same problem, I am calling WebAPi and is getting this error. Adding following configuration in web.config for services solved my problem

    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/> <!-- add this -->
    </modules>

in web.config file solved my problem. This is How i was calling from client side

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(environment.ServiceUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    HttpResponseMessage response = client.DeleteAsync("api/Producer/" + _nopProducerId).Result;
    if (response.IsSuccessStatusCode)
    {
        string strResult = response.Content.ReadAsAsync<string>().Result;
    }
}

Go to applicationHost.config (usually under C:\Windows\System32\inetsrv\config) file and comment out the following line in applicationHost.config

1)Under <handlers>:

<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />

2)Also comment out the following module being referred by the above handler under <modules>

<add name="WebDAVModule" />

In my case, I missed to add {id} to the [Route("")] and I got the same error. Adding that fixed the problem for me: [Route("{id}")]


I had 405 error Method Not Allowed because I had omitted to make the Delete method on the WebApi controller public.

It took me a long time to find this (too long!) because I would have expected a Not Found error in this case, so I was incorrectly assuming that my Delete method was being denied.

The reason for Not Allowed rather than Not Found is that I also had a Get method for the same route (which will be the normal case when implementing REST). The public Get function is matched by the routing and then denied because of the wrong http method.

A simple error I know but it may save someone else some time.


Just to add. If this is your config

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }

please keep doing as Hugo said, and do not set Route attribute to the controller get method, this gave a problem in my case.


[HttpPost] attribute on the top of Delete method solved this issue for me:

[HttpPost]
public void Delete(int Id)
{
  //Delete logic
}

I had the similar issue but for PUT - none of the other suggestions worked for me.

However i was using int rather than the default string for the id. adding {id:int} to the route solved my problem.

    [Route("api/Project/{id:int}")]
    public async Task<IHttpActionResult> Put(int id, [FromBody]EditProjectCommand value)
    {
       ...
    }

We had to add custom headers to our web.config as our request had multiple headers that confused the API response.

<httpProtocol>
    <customHeaders>
        <remove name="Access-Control-Allow-Methods" />
        <remove name="Access-Control-Allow-Origin" />
        <remove name="Access-Control-Allow-Headers" />
    </customHeaders>
</httpProtocol>

참고URL : https://stackoverflow.com/questions/15619075/webapi-delete-not-working-405-method-not-allowed

반응형