.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)
{
}
}