【发布时间】:2016-12-30 11:15:21
【问题描述】:
我正在尝试从我的 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 调用都可以正常工作。我只对发布的授权有问题。知道为什么吗?
标签: c# angularjs authorization cross-domain