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";
  1.  

 

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值