在Angular.js中的H5页面调用Web api时跨域问题处理

时间:2022-09-15 10:37:44

/// <summary>
/// 被请求时
/// 在Angular.js中的H5页面调用Web api时跨域问题处理
/// </summary>
/// <param name="sender">请求者</param>
/// <param name="e">参数</param>
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "AccessCode, content-type");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}

注:一般在Global.asax文件中增加此代码即可!