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

 

posted @ 2020-03-30 11:10  代码沉思者  阅读(3185)  评论(1编辑  收藏  举报