我正在尝试从我的WebAPI设置一个授权调用。
方法如下:
[Authorize]
[DynamicAuthorizeGroupRoles(DRoles = "Failures")]
[HttpGet]
[Route("Authorization/Test")]
public HttpResponseMessage GetTest()
{
Logger.Write(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
return "Access granted".ToJSONResponse();
}
如果我直接从浏览器调用它,它工作正常。然而,当我从我的AngularJS页面执行此操作时,我得到以下错误:
跨源请求阻塞:同源策略不允许读取远程资源http://.../Authorization/Test。(原因:CORS头'Access-Control-Allow-Origin'不匹配'').*
我的配置是这样的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
cors.SupportsCredentials = true;
config.EnableCors(cors);
// Web API routes
config.MapHttpAttributeRoutes();
}
}
Globals.asax.cs:
protected void Application_BeginRequest(object sender, EventArgs e)
{
EnableCrossDomainCall();
}
/// <summary>
/// Enable cross domain call
/// To Use post requests between domain
/// </summary>
private void EnableCrossDomainCall()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");
}
}
我试了几次都没有成功。你知道为什么会这样或者我需要改变什么吗? 不是你的WebApi项目有CORS问题。在Angular所在站点的web根目录下放置一个跨域文件。如果您使用IIS服务网站,请添加<location path="crossdomain.xml">
<system.webServer>
<staticContent>
<clear />
<mimeMap fileExtension=".xml" mimeType="text/x-cross-domain-policy" />
</staticContent>
</system.webServer>
</location>
到主机网站的webconfig