Web API的CORS

时间:2023-03-08 23:55:09
Web API的CORS
 

Web API中进行跨域需要在请求头中加入允许跨域请求

Access-Control-Allow-Origin=*

上面代码代表允许所有跨域请求。当然也可以只允许某个站点进行跨域请求,只需将‘*’改为指定站定即可

Access-Control-Allow-Origin=“http://www.baidu.com”

当然我们可以将允许请求写成一个过滤器,即可让指定页面允许跨域请求

public class CORSFilterAttribute:AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
actionContext.Request.Headers.Add("Access-Control-Allow-Origin", "*");
}
}