繁体   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' 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有'Access-Control-Allow-Origin' header 存在于请求的资源。

捕获

这是我前面请求的代码:

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 中的代码:

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中我设置了这个:

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

在 applicationhost.config 中:

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

这是我的 controller:

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

这是控制台中的详细消息: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 日期: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:同一地点

这是我的 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

从您的启动 Cors 配置中删除

     .AllowCredentials();

并从 controller 操作中删除

 [EnableCors("CorsPolicy")]

但是您仍然有状态码:401。它与 Cors 无关。 这只是关于授权。 只需注释所有授权代码即可测试 CORS。 在此之后,您可以开始授权。

CORS 策略已阻止从源“http://localhost:4200”访问“http://localhost:23645/api/Toolbar/Search”处的 XMLHttpRequest:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin' header 存在于请求的资源上。

请注意,CORS 预检请求(使用 HTTP OPTIONS方法)用于检查 CORS 协议是否被理解以及服务器是否知道使用特定方法和标头。 并且 HTTP OPTIONS请求始终是匿名的,您启用了 Windows 身份验证并禁用了匿名访问,这将导致服务器无法正确响应预检请求。

要使用 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.

暂无
暂无

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

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