.net 6 处理跨域的三种方式

.net 6  处理跨域的三种方式:

1.方法里添加,允许跨域
HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

2.方法添加特性,允许跨域
[CustomCorsActionFilterAttribute]


3. program.cs 全局注入,允许跨域
builder.Services.AddCors(policy =>
{
policy.AddPolicy("CorsPolicy", opt => opt
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithExposedHeaders("X-Pagination"));
});

app.UseCors("CorsPolicy");

 

 

--------

.net6 跨域:
public class CustomCorsActionFilterAttribute : Attribute, IActionFilter
{

public void OnActionExecuting(ActionExecutingContext context)
{
context.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}

public void OnActionExecuted(ActionExecutedContext context)
{

}
}

posted @ 2022-04-17 22:48  大树2  阅读(3757)  评论(0编辑  收藏  举报