简体   繁体   English

Httppost 和 httpput 被 .net 核心 3.1 中的 CORS 阻止

[英]Httppost and httpput blocked by CORS in .net core 3.1

I have a problem when i make httppost and httput (httpget is OK) to an API .net core 3.1 by an Angular 10 front, the error in console application is the famous: Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I have a problem when i make httppost and httput (httpget is OK) to an API .net core 3.1 by an Angular 10 front, the error in console application is the famous: Access to XMLHttpRequest at 'http://localhost:23645/api /Toolbar/Search' from origin 'http://localhost:4200' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin' header 存在于请求的资源。

capture捕获

this the code of my front request:这是我前面请求的代码:

constructor(private Http: HttpClient) {
    this.header =  new HttpHeaders(
      {
        'content-type': 'application/json'
      }
    )

searchToolbar(search: string): Observable<ToolbarSearchResultItem[]> {
    
    return this.Http.post(this.url + '/myController/Search', { "search": search }, { headers: this.header, withCredentials:true}).pipe(tap((response: myTyoe[]) => {
      return response;
    }));

this is my code in Startup.cs:这是我在 Startup.cs 中的代码:

public void ConfigureServices(IServiceCollection services)
        {
            log.Info("ConfigureServices");
            try
            {
                IConfigurationRoot configurationRoot = builder.Build();

                services.AddCors(opt => opt.AddPolicy("CorsPolicy", c =>
                {
                    c.WithOrigins("http://localhost:4200")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials();
                

            }));
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("AllUsers", policy => policy.RequireAuthenticatedUser());
                });
                
            services.AddControllers();

            services.AddMvc();

            }
            catch (Exception ex)
            {
                log.Error("Error in ConfigureServices" + ex.Message + ex.StackTrace);
            }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    try
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseRouting();

        app.UseCors("CorsPolicy");
        app.UseAuthorization();

in a launchSettings.json i set this:在launchSettings.json中我设置了这个:

"iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": false,
    "iisExpress": {
      "applicationUrl": "http://localhost:23645",
      "sslPort": 0
    }

and in applicationhost.config:在 applicationhost.config 中:

 <windowsAuthentication enabled="true">
          <providers>
            <add value="Negotiate" />
            <add value="NTLM" />
          </providers>
        </windowsAuthentication>

this is my controller:这是我的 controller:

 [HttpPost]
        [Route("Search")]
       [EnableCors("CorsPolicy")]
        public IList<ToolbarSearchResultItem> Search(ToolbarSearch search)
        {
//my code
}

this is the detailled message in the console:Request URL: http://localhost:23645/api/Toolbar/Search Request Method: OPTIONS Status Code: 401 Unauthorized Remote Address: [::1]:23645 Referrer Policy: strict-origin-when-cross-origin Cache-Control: private Content-Length: 6284 Content-Type: text/html;这是控制台中的详细消息:Request URL: http://localhost:23645/api/Toolbar/Search Request Method: OPTIONS Status Code: 401 Unauthorized Remote Address: [::1]:23645 Referrer Policy: -when-cross-origin Cache-Control: private Content-Length: 6284 Content-Type: text/html; charset=utf-8 Date: Tue, 02 Mar 2021 15:52:05 GMT Server: Microsoft-IIS/10.0 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-Powered-By: ASP.NET Accept: / Accept-Encoding: gzip, deflate, br Accept-Language: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7 Access-Control-Request-Headers: content-type Access-Control-Request-Method: POST Connection: keep-alive Host: localhost:23645 Origin: http://localhost:4200 Referer: http://localhost:4200/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: same-site charset=utf-8 日期:2021 年 3 月 2 日星期二 15:52:05 GMT 服务器:Microsoft-IIS/10.0 WWW-Authenticate: Negotiate WWW-Authenticate: NTLM X-Powered-By: ASP.NET Accept: / Accept-Encoding: gzip , 放气, br 接受语言: fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7 Access-Control-Request-Headers: content-type Access-Control-Request-Method: POST Connection: keep-alive Host: localhost:23645 Origin: http://localhost:4200 Referer: http://localhost:4200/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site:同一地点

this is my web.config这是我的 web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath=".\MYEXE.exe" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

I think that it is not really a CORS block problem but a configuration problem or other, it is very similar to this question: Trouble with CORS Policy and .NET Core 3.1 but I used a profiler and I don't have an SQL Problem I think that it is not really a CORS block problem but a configuration problem or other, it is very similar to this question: Trouble with CORS Policy and .NET Core 3.1 but I used a profiler and I don't have an SQL Problem

Remove from your startup Cors config从您的启动 Cors 配置中删除

     .AllowCredentials();

and remove from the controller actions并从 controller 操作中删除

 [EnableCors("CorsPolicy")]

But you still have have Status Code: 401. It has nothing to do with Cors.但是您仍然有状态码:401。它与 Cors 无关。 It is only about authorization.这只是关于授权。 Just comment all authorization code to test CORS.只需注释所有授权代码即可测试 CORS。 After this you can start with authorization.在此之后,您可以开始授权。

Access to XMLHttpRequest at 'http://localhost:23645/api/Toolbar/Search' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:23645/api/Toolbar/Search”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin' header 存在于请求的资源上。

Please note that a CORS preflight request (using the HTTP OPTIONS method) is used to check whether the CORS protocol is understood and a server is aware using specific methods and headers.请注意,CORS 预检请求(使用 HTTP OPTIONS方法)用于检查 CORS 协议是否被理解以及服务器是否知道使用特定方法和标头。 And the HTTP OPTIONS requests are always anonymous , you enabled Windows Authentication and disabled anonymous access, which would cause server not correctly respond to the preflight request.并且 HTTP OPTIONS请求始终是匿名的,您启用了 Windows 身份验证并禁用了匿名访问,这将导致服务器无法正确响应预检请求。

To run your app(s) on local for testing purpose with CORS, to fix this issue, you can try to enable anonymous authentification to allow anonymous access.要使用 CORS 在本地运行您的应用程序以进行测试,要解决此问题,您可以尝试启用匿名身份验证以允许匿名访问。

Besides, if you would host your app(s) on IIS server, to fix this issue, you can install IIS CORS module and configure CORS for the app. Besides, if you would host your app(s) on IIS server, to fix this issue, you can install IIS CORS module and configure CORS for the app.

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

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