NET Core 3.1中的CORS阻止了Httppost和httpput [英] Httppost and httpput blocked by CORS in .net core 3.1

查看:319
本文介绍了NET Core 3.1中的CORS阻止了Httppost和httpput的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我通过Angular 10前端向API .net core 3.1进行httppost和httput(httpget可以)时,我遇到了问题,控制台应用程序中的错误是著名的:通过CORS策略已阻止从源"http://localhost:4200"访问"http://localhost:23645/api/Toolbar/Search"处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:否请求的资源上显示"Access-Control-Allow-Origin"标头.

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.

捕获

这是我前面请求的代码:

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;
    }));

这是我在Startup.cs中的代码:

this is my code in 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();

在launchSettings.json中,我将其设置为:

in a launchSettings.json i set this :

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

并在applicationhost.config中:

and in applicationhost.config:

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

这是我的控制者:

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

这是控制台中的详细消息:请求URL:http://localhost:23645/api/Toolbar/Search请求方法:OPTIONS状态码:401未经授权远程地址:[:: 1]:23645推荐人政策:严格原产地-跨原产地缓存控制:私有内容长度:6284内容类型:text/html;字符集= utf-8日期:2021年3月2日,星期二,格林尼治标准时间服务器:Microsoft-IIS/10.0WWW认证:协商WWW认证:NTLMX-Powered-by:ASP.NET接受:/接受编码:gzip,deflate,br接受语言:fr-FR,fr; q = 0.9,en-US; q = 0.8,en; q = 0.7访问控制请求标头:内容类型访问控制请求方法:POST连接:保持活动状态主机:localhost:23645来源:http://localhost:4200引荐来源:http://localhost:4200/秒提取目标:空安全提取模式:cors安全提取站点:相同站点

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; 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

这是我的web.config

this is my 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>

我认为这实际上不是CORS阻止问题,而是配置问题或其他问题,它与以下问题非常相似:

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

推荐答案

CORS策略已阻止从来源"http://localhost:4200"访问"http://localhost:23645/api/Toolbar/Search"处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:所请求的资源上没有"Access-Control-Allow-Origin"标头.

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

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

要在本地运行应用以进行CORS测试,要解决此问题,您可以尝试启用匿名身份验证以允许匿名访问.

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.

此外,如果要在IIS服务器上托管应用程序以解决此问题,则可以安装

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.

这篇关于NET Core 3.1中的CORS阻止了Httppost和httpput的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆