asp.net core 3.1 解決跨域的問題


我的使用場景:
在本地建立了一個html文件,通過ajax訪問asp.net core 3.1提供的webapi服務。
在調試時,發現用html訪問拋了cors異常。

拋這樣的錯誤:
Access to XMLHttpRequest at 'http://localhost:52156/api/Person/1' from origin 'null' 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.

jquery-1.10.2.min.js:23 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost:52156/api/Person/1 with MIME type text/plain.

在微軟網站
查到,asp.net core cors 3.1的做法如下 :
在Startup類里面:

1.添加

 readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
 public void ConfigureServices(IServiceCollection services)
        {

            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins ,
                    builder => builder.AllowAnyOrigin()
/*
根據自己情況調整
 builder.WithOrigins("http://example.com",
                                    "http://www.contoso.com");

如果同時打開 AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()); 可只打開前兩個
會拋下面這個異常:
System.InvalidOperationException: Endpoint AnXin.DigitalFirePlatform.WebApi.Controllers.StaticPersonController.Get (AnXin.DigitalFirePlatform.WebApi) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...).
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
*/
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());

            });

            services.AddControllers();         
        }

3.Configure(IApplicationBuilder app, IHostingEnvironment env)方法里添加一行:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        //主要就是這兩行,但是要注意,這一行要在app.UseRouting 和 UseEndpoints 之間
        app.UseRouting();
        app.UseCors(MyAllowSpecificOrigins); 
        app.UseEndpoints(endpoints =>
            {           
 endpoints.MapControllers().RequireCors(MyAllowSpecificOrigins);
            });
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM