ASP.NET 웹 API-PUT 및 DELETE 동사 허용되지 않음-IIS 8
최근에 Visual Studio 2010에서 Visual Studio 2012 RC로 업그레이드했습니다. 설치 관리자는 이제 Visual Studio에서 기본 웹 서버로 사용하는 IIS 8 Express도 설치합니다.
IIS 8에서 PUT 및 DELETE 동사를 사용하는 WEB API 요청을 차단하고 있습니다. IIS는 405 오류를 반환합니다 The requested resource does not support http method 'PUT'
.
과거에 사람들이 이것에 문제가 있다는 것을 알고 스택 오버플로에 몇 가지 메시지가 있습니다. IIS 7 Express에서 솔루션은 WebDav를 제거하는 것이 었습니다. 불행히도 IIS 8에서는 그렇게 할 수 없습니다.
applicationhost.config에서 WebDav 섹션을 편집하려고 시도했지만 도움이되지 않았습니다. 예를 들어 <add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
구성 파일에서 제거 했습니다.
나는 이것에 너무 오래 보냈다. PUT 및 DELETE를 활성화하는 간단한 방법이 있어야합니까?
괜찮아. 나는 마침내 이것의 바닥에 도착했다. IIS8에서 PUT 및 DELETE 동사가 올바르게 작동하려면 일부 후프를 뛰어 넘어야합니다. 실제로 VS 2012의 릴리스 후보를 설치하고 새 WEB API 프로젝트를 작성하면 샘플 PUT 및 DELETE 메소드가 기본적으로 404 오류를 리턴 함을 알 수 있습니다.
웹 API와 함께 PUT 및 DELETE 동사를 사용하려면 다음과 같이 % userprofile % \ documents \ iisexpress \ config \ applicationhost.config를 편집하고 ExtensionlessUrl 핸들러에 동사를 추가해야합니다.
이 줄을 바꾸십시오 :
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
에:
<add name="ExtensionlessUrl-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
위의 사항 외에도 WebDAV가 요청을 방해하지 않아야합니다. applicationhost.config에서 다음 행을 주석 처리하여 수행 할 수 있습니다.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />
<add name="WebDAVModule" />
<add name="WebDAV" path="*" verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK" modules="WebDAVModule" resourceType="Unspecified" requireAccess="None" />
또한 기본 웹 API 규칙은 메소드 이름이 호출 된 HTTP 동사와 동일해야한다는 것입니다. 예를 들어 HTTP 삭제 요청을 보내는 경우 기본적으로 메소드 이름은 Delete로 지정해야합니다.
아래와 같이 Web.Config 파일을 변경하십시오. 그것은 매력처럼 행동 할 것입니다.
노드에서 <system.webServer>
아래 코드 부분 추가
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
추가하면 Web.Config는 다음과 같습니다.
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule"/>
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
<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>
WebDAV를 제거하면 내 경우에는 완벽하게 작동합니다.
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.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>
iis 또는 machine.config를 통해 문제를 해결하는 대신 항상 web.config를 통해 문제를 해결하는 것이 좋습니다. 앱이 다른 컴퓨터에서 호스팅되는 경우 발생하지 않을 것입니다.
web.config 업데이트
<system.webServer>
<modules>
<remove name="WebDAVModule"/>
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrl-Integrated-4.0" />
<add name="ExtensionlessUrl-Integrated-4.0"
path="*."
verb="GET,HEAD,POST,DEBUG,DELETE,PUT"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
호스트 구성을 수정할 필요가 없습니다.
Asp.Net 웹 API에서-webconfig. 이것은 모든 브라우저에서 작동합니다.
System.web 태그 안에 다음 코드를 추가하십시오.
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
아래 코드로 system.webserver 태그를 바꾸십시오
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="false">
<remove name="WebDAVModule" />
</modules>
<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" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
이것은 다른 답변과 함께 iis8에서 나를 위해 일했습니다. 내 오류는 구체적으로 404.6이었다
<system.webServer>
<security>
<requestFiltering>
<verbs applyToWebDAV="false">
<add verb="DELETE" allowed="true" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
이 문제가 발생할 수있는 다른 사용자를위한 빠른 업데이트입니다. 오늘 현재 % userprofile % \ documents \ iisexpress \ config \ applicationhost.config를 변경해도 더 이상 작동하지 않습니다 (지금까지는 Windows 업데이트로 인한 것인지 확실하지 않습니다). 몇 시간 동안 좌절을 겪은 후 web.config를 변경하여 작동하도록 system.webserver에 이러한 핸들러를 추가했습니다.
<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>
CORS 활성화 (좋고 깔끔함)
1. CORS nuget 패키지 추가
Install-Package microsoft.aspnet.webapi.cors
2. WebApiConfig.cs 파일에서 등록 방법에 다음 코드를 추가하십시오.
config.EnableCors();
예 :
System.Web.Http 사용;
namespace test
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors(); //add this**************************
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
컨트롤러의 네임 스페이스에 다음 코드를 추가하면 get, post, delete, put 또는 http 메소드가 포함됩니다.
[EnableCors(origins: "The address from which the request comes", headers: "*", methods: "*")]
전의:
using System.Web.Http.Cors;//add this******************************
namespace Test.Controllers
{
[EnableCors(origins: "http://localhost:53681/HTML/Restaurant.html", headers: "*", methods: "*")]
public class RestaurantController : ApiController
{
protected TestBusinessLayer DevTestBLL = new TestBusinessLayer();
public List<Restaurant> GET()
{
return DevTestBLL.GetRestaurant();
}
public List<Restaurant> DELETE(int id)
{
return DevTestBLL.DeleteRestaurant(id);
}
}
}
참조 : http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
아무것도 효과가 없으면 아래 단계를 통해이 문제를 해결할 수있었습니다.
• IIS를 설치하는 동안 'WEB DAV PUBLISHING'IIS 설정을 선택하지 않았습니다. • INETMGR-기본 웹 사이트 – 요청 필터링 – HTTP 동사 – PUT을 True로
끝없이 검색하고 이미 제공된 답변 (PUT, DELETE 동사 추가 및 WEBdav 제거)을 시도한 후에는 작동하지 않았습니다.
IIS 로깅 설정으로 이동했습니다 :> 로그 파일보기. 필자의 경우 W3SVC4는 최신 날짜의 폴더이며 폴더를 열고 최신 로그 파일을 조회 한 후 다음 항목을 확인했습니다. GET / Rejected-By-UrlScan ~ / MYDOMAIN / API / ApiName / UpdateMETHOD
업데이트 방법이 동사 GET과 함께 나열되었습니다. 그래서 나는 거부로 UrlScan을 검색 하고이 링크를 찾았습니다 : UrlScan Broke My Blog .
나는 여기에 갔다 : % windir % \ system32 \ inetsrv \ urlscan \ UrlScan.ini
기본적으로 UrlScan은 PUT 및 DELETE 동사를 차단했습니다. 이 INI 파일을 열고 PUT 및 DELETE를 AllowVerbs에 추가하고 DenyVerbs 목록에서 제거했습니다. INI 파일을 저장했는데 작동했습니다! 그래서 나를 위해 ExtensionlessUrlHandler 힌트 옆 에이 단계가 필요했습니다.
Windows Webserver 2008 R2 (64 비트), IIS 7.5 DotNetNuke (DNN) WebAPI와 함께 이것을 사용하고 있습니다. ASP.Net 4.0 내 업데이트 방법 :
[HttpPut]
[DnnAuthorize(StaticRoles = "MyRoleNames")]
public HttpResponseMessage UpdateMETHOD(DTO.MyObject myData)
PHP의 경우 다음과 같습니다.
- IIS 열기
- 핸들러 매핑으로 이동
- php5.6.x 또는 php7.0.x에서 편집을 클릭하십시오
- "요청 제한"을 클릭하십시오
- under the verbs tab, select "one of the following verbs" and add "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS"
I imagine this will work with other handlers too.
Besides all above solutions, check if you have the "id" or any custom defined parameter in the DELETE method is matching the route config.
public void Delete(int id)
{
//some code here
}
If you hit with repeated 405 errors better reset the method signature to default as above and try.
The route config by default will look for id in the URL. So the parameter name id is important here unless you change the route config under App_Start folder.
You may change the data type of the id though.
For example the below method should work just fine:
public void Delete(string id)
{
//some code here
}
Note: Also ensure that you pass the data over the url not the data method that will carry the payload as body content.
DELETE http://{url}/{action}/{id}
Example:
DELETE http://localhost/item/1
Hope it helps.
I have faced the same issue with you, then solved it, Here are solutions, I wish it maybe can help
First
In the IIS modules
Configuration, loop up the WebDAVModule, if your web server has it, then remove it
Second
In the IIS handler mappings
configuration, you can see the list of enabling handler, to choose the PHP item
, edit it, on the edit page, click request restrictions button, then select the verbs tab
in the modal, in the specify the verbs to be handle label, check the all verbs radio
, then click ok, you also maybe see a warning, it shows us that use double quotation marks to PHP-CGI execution, then do it
if done it, then restart IIS server, it will be ok
I am not sure if you have edited right configuration file. Try following steps
open %userprofile%\ducuments\iisexpress\config\applicationhost.config
By default bellow given entries are commented in the applicationhost.config file. uncomment these entries.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /> <add name="WebDAVModule" />
<add name="WebDAV" path="*"
verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK"
modules="WebDAVModule" resourceType="Unspecified" requireAccess="None"
/>
Here is how you allow extra HTTP Verbs using the IIS Manager GUI.
In IIS Manager, select the site you wish to allow PUT or DELETE for.
Click the "Request Filtering" option. Click the "HTTP Verbs" tab.
Click the "Allow Verb..." link in the sidebar.
In the box that appears type "DELETE", click OK.
Click the "Allow Verb..." link in the sidebar again.
In the box that appears type "PUT", click OK.
I am using an ashx file in an MVC application and none of the above answers worked for me. IIS 10.
Here's what did work. Instead of changing "ExtensionlessUrl-Integrated-4.0" in IIS or web.config I changed "SimpleHandlerFactory-Integrated-4.0" for "*.ashx" files:
<add name="SimpleHandlerFactory-Integrated-4.0" path="*.ashx"
verb="GET,HEAD,POST,DEBUG,PUT,DELETE"
type="System.Web.UI.SimpleHandlerFactory"
resourceType="Unspecified" requireAccess="Script"
preCondition="integratedMode,runtimeVersionv4.0" />
The another reason can be the following:
I changed my Url for Web Api method according to this answer:
Url.Action("MyAction", "MyApiCtrl", new { httproute = "" })
But this method creates link like:
/api/MyApiCtrl?action=MyAction
This works correctly with GET and POST requests but not with PUT or DELETE.
So I just replaced it with:
/api/MyApiCtrl
and it fixed the problem.
In IIS 8.5/ Windows 2012R2, Nothing mentioned here worked for me. I don't know what is meant by Removing WebDAV but that didn't solve the issue for me.
What helped me is the below steps;
- I went to IIS manager.
- In the left panel selected the site.
- In the left working area, selected the WebDAV, Opened it double clicking.
- In the right most panel, disabled it.
Now everything is working.
You can convert your Delete method as POST as;
[HttpPost]
public void Delete(YourDomainModel itemToDelete)
{
}
참고URL : https://stackoverflow.com/questions/10906411/asp-net-web-api-put-delete-verbs-not-allowed-iis-8
'IT' 카테고리의 다른 글
안드로이드와 텍스트 센터를 정렬 (0) | 2020.06.22 |
---|---|
모든 훌륭한 Java / Java EE 개발자가 대답 할 수있는 질문이 있습니까? (0) | 2020.06.22 |
장고 템플릿의 숫자 형식 (0) | 2020.06.21 |
PhoneGap / Cordova로 Android를 빌드 할 때 Mac OS X 10.9 Mavericks에서 'ant'명령 실행 오류 (0) | 2020.06.21 |
일정 시간 동안 작업이 없으면 자동으로 페이지를 다시로드하는 방법 (0) | 2020.06.21 |