我正在尝试从我的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标题'访问控制 - 允许 - 来源'不匹配' ')。*
这就是我的配置的样子:
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");
}
}
我尝试了几次尝试没有成功。知道为什么会这样或者我需要改变什么吗?
答案 0 :(得分:0)
这不是您的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