ASP.NET Core 利用中间件支持跨域请求

本文介绍了两种在ASP.NET Core中实现跨源资源共享(CORS)的方法。第一种是在Startup类的ConfigureServices()和Configure()方法中使用内置的CORS策略。第二种是通过自定义中间件实现更精细的CORS控制。

方法1:

在Startup的ConfigureServices()中添加services.AddCors()
在Startup的Configure()中添加app.UseCors(); 保证其在app.UseMvc();之前

app.UseCors(builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());   
app.UseMvc();
原文链接

https://stackoverflow.com/questions/44379560/how-to-enable-cors-in-asp-net-core-webapi

 

方法2:

1、public void Configure(IApplicationBuilder app, IHostingEnvironment env)方法里面

不要加上:app.UseCors();

2、上面方法加上:

app.UseMiddleware<CorsMiddleware>();

3、中间代码如下:

public class CorsMiddleware
{
    private readonly RequestDelegate next;

    public CorsMiddleware(RequestDelegate next)
    {
        this.next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
        {
            context.Response.Headers.Add("Access-Control-Allow-Origin", context.Request.Headers["Origin"]);
            context.Response.Headers.Add("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,HEAD,PATCH");
            context.Response.Headers.Add("Access-Control-Allow-Headers", context.Request.Headers["Access-Control-Request-Headers"]);
            context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");

            if (context.Request.Method.Equals("OPTIONS"))
            {
                context.Response.StatusCode = StatusCodes.Status200OK;
                return;
            }
        }

        await next(context);
    }
}

转载于:https://www.cnblogs.com/wmlunge/p/10655209.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值