ASP.NET - Enable CORS

允许 WebApi 跨域

  • 方法1,编辑 web.config
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="*" />
      <add name="Access-Control-Allow-Methods" value="*" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
  • 方法2,添加包Microsoft.AspNet.WebApi.Cors,然后再WebApiConfig.cs中添加允许跨域设置
public static void Register(HttpConfiguration config)
{
  config.EnableCors(new EnableCorsAttribute("*","*","*"));
  ...
}

允许 MVC 跨域

  • 方法1,编辑web.config
<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
    </customHeaders>
  </httpProtocol>
</system.webServer>
  • 方法2,增加一个跨域的属性Class
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

然后对Controller的方法加上属性标签,这样返回的Response的Header就会增加跨域访问的字段

[AllowCrossSiteJson]
[HttpPost]
public JsonResult QueryResult()
{
    return Json(q, JsonRequestBehavior.AllowGet);
}