简体   繁体   English

In.Net Core 2.1 Web API 用于 PUT 和 DELETE,仅为什么请求的资源上存在“No 'Access-Control-Allow-Origin' header”

[英]In .Net Core 2.1 Web API for PUT and DELETE only why “No 'Access-Control-Allow-Origin' header is present on the requested resource”

I am using .NET Core 2.1.我正在使用 .NET Core 2.1。 I have configured Startup.cs as follow:我已将 Startup.cs 配置如下:

public class Startup
{   
     public static IConfiguration Configuration { get; private set; }

     public Startup(IConfiguration configuration)
     {
         Configuration = configuration;
     }


     public void ConfigureServices(IServiceCollection services)
     {
         services.AddCors();
         services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     }

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
     {
         app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

         if (env.IsDevelopment())
         {
             app.UseDeveloperExceptionPage();
         }

         app.UseMvc();
     }
 }

Web API is deployed on linux machine. Web API部署在linux机器上。 GET and POST methods are working fine. GETPOST方法工作正常。 When I try to call PUT or DELETE this message is being generated in Chroome console.当我尝试调用PUTDELETE时, Chroome控制台中会生成此消息。

Access to XMLHttpRequest at 'http://IP' from origin 'http://IP' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Initially Kestrel was listing on 50001 beacuse SSL certificate was present.最初,Kestrel 列在50001上,因为存在 SSL 证书。 I configured Kestrel in appsettings.json to listen only on 5000 .我在appsettings.json Kestrel 配置为仅在5000上收听。 So now its only listing on 5000 .所以现在它只在5000上市。

appsettings.json appsettings.json

{
    "Kestrel": {
        "EndPoints": {
            "Http": {
                "Url": "http://localhost:5000"
            }
        }
    }
}

I've tried almost every answer given in this thread How to enable CORS in ASP.net Core WebAPI我已经尝试了这个线程中给出的几乎所有答案How to enable CORS in ASP.net Core WebAPI

None of them worked in my case.他们都没有在我的情况下工作。

Origin is my localhost and Web API is on Live IP. Origin是我的本地主机,Web API 正在直播 IP。

EDIT 1编辑 1

Preflight (OPTIONS) Response Headers预检 (OPTIONS) 响应标头

HTTP/1.1 204 No Content
Server: nginx/1.14.0 (Ubuntu)
Date: Sat, 25 Apr 2020 18:50:50 GMT
Connection: keep-alive
Access-Control-Allow-Headers: authtoken,authuser,content-type
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Origin: *

Preflight (OPTIONS) Request Headers预检 (OPTIONS) 请求标头

OPTIONS /Foo/Controller HTTP/1.1
Host: MY LINUX Machine Live IP
Connection: keep-alive
Access-Control-Request-Method: PUT
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
Access-Control-Request-Headers: authtoken,authuser,content-type
Accept: */*
Referer: http://localhost:8080/xyz
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

Actual Request (Request Headers)实际请求(请求标头)

PUT /Foo/Controller HTTP/1.1
Host: Linux IP
Connection: keep-alive
Content-Length: 63
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
Content-Type: application/json
Referer: http://localhost:8080/xyz
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9

Actual Request (Response Headers)实际请求(响应标头)

HTTP/1.1 500 Internal Server Error
Content-Type: text/html
Content-Length: 225
Connection: Close

.NET Core enables the WebDAVModule, which disables PUT and DELETE requests by default. .NET Core 启用 WebDAVModule,默认情况下禁用 PUT 和 DELETE 请求。 So, to solve the issue, I ended up disabling WebDAV in the whole application, by adding these lines to the auto-generated web.config:所以,为了解决这个问题,我最终在整个应用程序中禁用了 WebDAV,将这些行添加到自动生成的 web.config 中:

<system.webServer></system.webServer> <system.webServer></system.webServer>

With the specific failures being on the PUT and DELETE calls, it sounds like you're still running into issues with preflight requests由于 PUT 和 DELETE 调用出现特定故障,听起来您仍然遇到预检请求问题

Per https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1#preflight-requests-1 :根据https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.1#preflight-requests-1

Preflight requests For some CORS requests, the browser sends an additional request before making the actual request.预检请求 对于某些 CORS 请求,浏览器会在发出实际请求之前发送一个附加请求。 This request is called a preflight request.该请求称为预检请求。 The browser can skip the preflight request if the following conditions are true:如果满足以下条件,浏览器可以跳过预检请求:

  • The request method is GET, HEAD, or POST.请求方法是 GET、HEAD 或 POST。
  • The app doesn't set request headers other than Accept, Accept-Language, Content-Language, Content-Type, or Last-Event-ID.除了 Accept、Accept-Language、Content-Language、Content-Type 或 Last-Event-ID 之外,该应用不会设置请求标头。
  • The Content-Type header, if set, has one of the following values: Content-Type header(如果设置)具有以下值之一:
    • application/x-www-form-urlencoded应用程序/x-www-form-urlencoded
    • multipart/form-data多部分/表单数据
    • text/plain文本/纯文本

It's difficult to troubleshoot specifically with what you have above alone without knowing whether there's anything like nginx or some other reverse proxy between Kestrel and the web that may be impacting headers.在不知道是否有类似 nginx 或 Kestrel 和 web 之间的其他反向代理可能会影响标头的情况下,很难单独使用上述内容进行故障排除。 During testing, this article from Rick Strahl also presents a good reminder during local or non-cross origin testing:在测试过程中,Rick Strahl 的这篇文章在本地或非跨域测试中也提出了一个很好的提醒:

https://weblog.west-wind.com/posts/2016/sep/26/aspnet-core-and-cors-gotchas#Watch-out-for-testing-CORS-without-Cross-Domain ! https://weblog.west-wind.com/posts/2016/sep/26/aspnet-core-and-cors-gotchas#Watch-out-for-testing-CORS-without-Cross-Domain

CORS headers are only sent on cross domain requests and the ASP.NET CORS module is smart enough to detect whether a same domain request is firing and if it is, doesn't send the headers. CORS 标头仅在跨域请求时发送,ASP.NET CORS 模块足够智能,可以检测是否触发了相同的域请求,如果是,则不发送标头。

When checking that error out in Chrome, make sure you're able to take a look at the calls being made and confirm any preflight OPTIONS calls contain the headers being looked for.在 Chrome 中检查该错误时,请确保您能够查看正在进行的调用并确认任何预检 OPTIONS 调用都包含正在查找的标头。 This StackOverflow link describes enabling showing the OPTIONS requests in debug:此 StackOverflow 链接描述了启用在调试中显示 OPTIONS 请求:

https://stackoverflow.com/a/57669710/13374279 https://stackoverflow.com/a/57669710/13374279

Resolved by adding the following settings to web.config通过将以下设置添加到 web.config 解决

[1]:https://i.stack.imgur.com/Lyeph.png

Tried below on .net core web API下面在 .net 核心 web API 上尝试过

Yes, you can add <modules runAllManagedModulesForAllRequests="false"> <remove name="WebDAVModule" /> </modules>是的,您可以添加<modules runAllManagedModulesForAllRequests="false"> <remove name="WebDAVModule" /> </modules>

inside <system.webServer> tag of your auto-generated web.config file (config file is creating once you hosted the API)在自动生成的 web.config 文件的<system.webServer>标记内(托管 API 后将创建配置文件)

屏幕

Please note below for CORS in your .net core API's startup class请注意以下 .net 核心 API 的启动 class 中的 CORS

--in ConfigureServices Method --in 配置服务方法

 services.AddCors();
 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

--in Configure Method --in 配置方法

app.UseCors(Options =>
                   Options.WithOrigins("your client URL")
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                  
              );


            app.UseAuthentication();  //for JWT
            app.UseMvc();

暂无
暂无

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

相关问题 .NET Core 中请求的资源上不存在“Access-Control-Allow-Origin”header - No 'Access-Control-Allow-Origin' header is present on the requested resource in .NET Core React+ASP.NET.Core:请求的资源上不存在“Access-Control-Allow-Origin”标头 - React+ASP.NET.Core : No 'Access-Control-Allow-Origin' header is present on the requested resource ASP.Net核心WebAPI - 请求的资源上没有“Access-Control-Allow-Origin”标头 - ASP.Net Core WebAPI - No 'Access-Control-Allow-Origin' header is present on the requested resource ASP.NET Web窗体:所请求的资源上不存在“ Access-Control-Allow-Origin”标头 - ASP.NET Web Forms: No 'Access-Control-Allow-Origin' header is present on the requested resource Web API中的请求资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource in web api c#已启用CORS的Web Api和所请求资源上存在可怕的“Access-Control-Allow-Origin”标头 - c# Web Api with CORS Enabled and the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource MVC web api:请求的资源上不存在“Access-Control-Allow-Origin”标头 - MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource CORS所请求的资源上没有“ Access-Control-Allow-Origin”标头 - CORS No 'Access-Control-Allow-Origin' header is present on the requested resource CORS - 没有'Access-Control-Allow-Origin' header 存在于请求的资源上 - CORS - No 'Access-Control-Allow-Origin' header is present on the requested resource 请求的资源上不存在“ Access-Control-Allow-Origin”标头 - No 'Access-Control-Allow-Origin' header is present on the requested resource
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM