簡體   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