簡體   English   中英

在 IIS 上部署后,asp.net core web api 上的 CORS 不起作用

[英]CORS on asp.net core web api doesn't work after deploy on IIS

我正在開發一個帶有角度前端的網絡核心 webapi。 當我調試一切正常時,現在我已經在 IIS 上部署了 web abi 我無法讓它工作,它給了我 CORS 錯誤: "...No 'Access-Control-Allow-Origin' header is present on the requested resource."

這是在 web api 上啟用 CORS 的代碼:

public void ConfigureServices(IServiceCollection services)
{
...
    services.AddCors();

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

我嘗試了在本網站和其他網站上找到的不同解決方案,但似乎沒有任何效果

我應該在我的 angular 應用程序中添加某種標題嗎? 問題可能出在 IIS 上嗎?

你可能想看看這個。

在您的 Startup.cs 文件中

// This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
           services.AddCors(cfg =>
           {
                cfg.AddDefaultPolicy(policy =>
                {
                     policy.WithOrigins("list of origins to allow here")
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .AllowCredentials()
                     .SetIsOriginAllowed((_) => true)
                     .SetIsOriginAllowedToAllowWildcardSubdomains();
                });
           });


services.AddMvc()
                .AddJsonOptions(options =>
                {
                     options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                     options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                     options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
      }


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
         app.UseCors();
         app.UseMvc(routes =>
           {
                routes.MapRoute(
                     name: "default",
                     template: "{controller=Home}/{action=Index}/{tag?}");
           });
      }

請確保在調用 MVC 之前調用 Cors。

我希望這有幫助。

問候

我終於設法解決了這個問題:我在 IIS 上啟用了“基本身份驗證”,因為我錯誤地認為這是正確的做法。

我發現 IIS 的“基本身份驗證”與我實現的不同(我創建了一個自定義的“BasicAuthenticationHandler”來讀取標頭和驗證用戶)

問題是,即使啟用了“匿名身份驗證”(禁用所有其他身份驗證是強制性的),IIS(或 Angular 或 Chrome,我不知道)而不是返回錯誤“401 未經授權”給了我 CORS 錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM