简体   繁体   English

DELETE/PUT 动词导致 404 Not Found in WebAPI,仅在本地运行时

[英]DELETE/PUT verbs result in 404 Not Found in WebAPI, only when running locally

I know this is a commonly addressed issue, and I've done everything that many posts here on SO suggest.我知道这是一个经常解决的问题,我已经做了很多关于 SO 的帖子所建议的一切。 When I try to delete a record using WebAPI (version 2) from my MVC5 front end running under local IIS, I get a 404 Not Found response.当我尝试从在本地 IIS 下运行的 MVC5 前端使用 WebAPI(版本 2)删除记录时,我收到 404 Not Found 响应。 Here are the things I've tried:以下是我尝试过的事情:

I've added the following under <system.webServer /> in my WebAPI web.config:我在我的 WebAPI web.config 中的<system.webServer />下添加了以下内容:

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <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>
  </system.webServer>

I've followed the instructions at: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx , which basically say to modify the ExtensionlessUrlHandler-Integrated-4.0 in IIS "Handler Mappings".我已经按照以下说明操作: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx ,基本上说修改IIS“处理程序映射”中的ExtensionlessUrlHandler-Integrated-4.0 It says to double click on the handler, click "Request Restrictions", and "Allow PUT and DELETE verbs".它说要双击处理程序,单击“请求限制”和“允许 PUT 和 DELETE 动词”。 I've done this, and I still get the 404 error.我已经这样做了,但我仍然收到 404 错误。

I've done an IIS reset.我已经完成了 IIS 重置。

Here's my MVC5 front end code that calls the WebAPI delete method - please note that when I manually navigate to api/bulletinboard/get/{0} where {0} is an integer, I get a valid JSON response.这是我调用 WebAPI 删除方法的 MVC5 前端代码 - 请注意,当我手动导航到api/bulletinboard/get/{0} ,其中{0}是一个整数,我得到一个有效的JSON响应。 Below, contactUri is http://localhost/SiteName/api/bulletinboard/get/53 which returns valid JSON :下面, contactUrihttp://localhost/SiteName/api/bulletinboard/get/53 ,它返回有效的JSON

[HttpPost, ActionName("Delete")]
        public ActionResult Delete(string appId, int id)
        {
            response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
            contactUri = response.RequestMessage.RequestUri;
            response = client.DeleteAsync(contactUri).Result;

            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("MessageList", new { appId = appId });
            }
            else
            {
                LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
                    "Cannot delete message due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
                return View("Problem");
            }
        }

Here's my WebAPI delete method:这是我的 WebAPI 删除方法:

[HttpDelete]
        public HttpResponseMessage Delete(int id)
        {
            BulletinBoard bulletinBoard = db.BulletinBoards.Find(id);
            if (bulletinBoard == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.BulletinBoards.Remove(bulletinBoard);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, bulletinBoard);
        }

Here's my WebApiConfig.cs in my WebAPI project:这是我的 WebAPI 项目中的 WebApiConfig.cs:

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

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

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

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Formatters.Add(new PlainTextFormatter());
        }

QUESTION : What else can I try to resolve this error?问题:我还可以尝试什么来解决此错误? This works fine when deployed from my local environment to my company's development servers.当从我的本地环境部署到我公司的开发服务器时,这很好用。

for those who still looking for enable DELETE & PUT The below code solve my problem对于那些仍在寻找启用 DELETE & PUT 以下代码解决我的问题的人

<validation validateIntegratedModeConfiguration="false" />
<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

  <!--This will enable all Web API verbose-->
  <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>

I've followed the instructions at: https://forums.asp.net/t/1961593.aspx?DELETE+PUT+verbs+result+in+404+Not+Found+in+WebAPI+only+when+running+locally我已经按照以下说明操作: https : //forums.asp.net/t/1961593.aspx?DELETE+PUT+verbs+result+in+404+Not+Found+in+WebAPI+only+when+running+本地

That says to only change this piece of code in your Web.config, and works fine for me!这表示只更改 Web.config 中的这段代码,对我来说效果很好!

<system.webServer>
    <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>
    <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>

If you are using IIS, make sure you have the HTTP Verb set to allowed in Request Filtering.如果您使用的是 IIS,请确保在请求过滤中将 HTTP 动词设置为允许。 If its not there, you can set it to allow it on the side.如果它不在那里,您可以将其设置为允许它放在一边。

在此处输入图片说明

We were struggling with DELETE/PUT returning 404 errors on IIS 8. We did all of the above answers changing web.config to accept all Verbs, enabling put/delete in the request filtering.我们正在努力解决 DELETE/PUT 在 IIS 8 上返回 404 错误的问题。我们做了上述所有答案,将 web.config 更改为接受所有动词,在请求过滤中启用 put/delete。 We had also disabled webDAV multiple ways.我们还通过多种方式禁用了 webDAV。 We found that the application pool was set to classic verses integrated (what it should have been).我们发现应用程序池被设置为经典诗句集成(它应该是什么)。 Now DELETE/PUT verbs work fine.现在 DELETE/PUT 动词工作正常。

This issue can be fixed by IIS level configuration- Open IIS->select your website->IIS (section) ->Request Filtering ->HHTP Verbs这个问题可以通过 IIS 级别的配置来解决 - 打开 IIS-> 选择你的网站 -> IIS(部分) -> 请求过滤 -> HHTP 动词

Remove DELETE verb/ OR allow DELETE verb删除 DELETE 动词/或允许 DELETE 动词

Issue will get resolved.问题将得到解决。

What I did was just switch from using local IIS to IIS Express via the project properties on my WebAPI project, as a workaround.我所做的只是通过 WebAPI 项目上的项目属性从使用本地 IIS 切换到 IIS Express,作为一种解决方法。 Doing this and deleting a record then resulted in a 405 Method Not Allowed error.这样做并删除记录会导致 405 Method Not Allowed 错误。 I then changed the lines of code:然后我更改了代码行:

response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;

To:到:

response = client.DeleteAsync(string.Format("api/bulletinboard/delete/{0}", id)).Result;

This is very strange because I have another project that runs the first block of code and it deletes records just fine.这很奇怪,因为我有另一个项目运行第一个代码块,它删除记录就好了。 Anyways, this resolved my local problem.无论如何,这解决了我的本地问题。 I understand this doesn't really resolve my main issue which was using local IIS, but this workaround worked for me.我知道这并不能真正解决我使用本地 IIS 的主要问题,但这种解决方法对我有用。

Mark Jensen solution worked for me. Mark Jensen 解决方案对我有用。

Just changed my Application Pool from "Classic" to "Integrated" and my requests worked.刚刚将我的应用程序池从“经典”更改为“集成”,我的请求有效。

If your project is working under IIS and not under IISExpress, try to set IISExpress Managed Pipeline Mode to Integrated.如果您的项目在 IIS 下运行而不是在 IISExpress 下运行,请尝试将 IISExpress 托管管道模式设置为集成。 PUT and DELETE verbs seems to have problem under Classic Managed Pipeline mode. PUT 和 DELETE 动词在经典托管管道模式下似乎有问题。

Good luck..祝你好运..

Roberto.罗伯托。

对我来说,它是一个名为 UrlScan 的 ISAPI 模块,我必须从应用程序中完全删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM