[英]C# webapi Cors Option request in server returns error 404 not found
我面临 cors 问题,选项预检请求显示 404 未找到。 在我的本地环境中对此进行了测试,我的设置完全正常。 但是当我尝试在实际的 IIS 服务器中实现此功能时,选项预检请求显示 404 未找到。 我的 api 创建为 web api 项目。
我曾尝试按照其他帖子中的建议设置预检请求处理程序,但它仍然无法正常工作。 是否有任何特定原因仅在本地有效?
本节显示选项请求:
General Request URL: http://api.domain.cc/api/Login Request Method: OPTIONS Status Code: 404 Not Found Remote Address: 192.168.10.5:80 Referrer Policy: strict-origin-when-cross-origin Response Headers: HTTP/1.1 404 Not Found Content-Type: text/html X-Powered-By: ASP.NET Server: Domain Date: Tue, 30 Mar 2021 07:54:34 GMT Content-Length: 1245 Request Headers: OPTIONS /api/Login HTTP/1.1 Host: api.domain.cc Connection: keep-alive Pragma: no-cache Cache-Control: no-cache Accept: */* Access-Control-Request-Method: POST Access-Control-Request-Headers: authorization,content-type Origin: http://site.domain.cc User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Sec-Fetch-Mode: cors Referer: http://site.domain.cc/ Accept-Encoding: gzip, deflate Accept-Language: en-US,en;q=0.9,zh-TW;q=0.8,zh;q=0.7,zh-CN;q=0.6
我已经设置了我的 web.config 如下:
<system.webServer>
<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>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
</system.webServer>
我的 web api 配置如下:
public static void Register(HttpConfiguration config) { // Web API configuration and services EnableCorsAttribute cors = new EnableCorsAttribute( origins: "http://site.domain.cc", headers: "*", methods: "GET, POST, DELETE, PUT, OPTIONS") { SupportsCredentials = true }; config.EnableCors(cors); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
您可以先通过在 web 配置中设置允许的来源来测试您的 api controller 吗?
如果这也返回 404 not found 那么其他问题是问题而不是 CORS。
我设法最终解决了这个问题。 我在这里做了两件事。
我的 api 仍然为选项请求返回错误 404 的原因是因为我的应用程序池之前设置为“经典”模式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.