【发布时间】:2018-07-25 05:49:23
【问题描述】:
我目前正在编写一个 Angular 应用程序,它与使用 Web API 2 开发的服务器部分进行通信。
有时我想在查询的响应中添加一个特定的标头。 我已启用 CORS。
当调用来自同一个来源时,没问题,该值在响应标头中,我可以在角度方面威胁它。 当从另一个来源进行调用时,响应中的标头名称不可用。
在这两种情况下,当我通过 Chrome 中的开发人员工具检查查询时,我都会在响应中看到标题。
我做错了什么有什么想法吗? Angular 部分有什么特别的事情要做吗?
出于测试目的,我只是在 Web API 中执行此操作:
public static void Register(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
.....
// rest of the implementation (Routes, etc...)
}
更新
我写了一个 ICorsPolicyProvider :
public class IkCorsPolicyProvider : ICorsPolicyProvider
{
private CorsPolicy CreateCorsPolicy()
{
CorsPolicy policy = new CorsPolicy
{
AllowAnyMethod = true,
AllowAnyHeader = false,
AllowAnyOrigin = false
};
// Some code to get the client allowed origins
//.....
//
// set the allowed origins to the policy
foreach (string allowedOrigin in allowedOrigins)
{
policy.Origins.Add(allowedOrigin);
}
policy.Headers.Add("content-type");
policy.Headers.Add(UserContext.Key);
policy.ExposedHeaders.Add("content-type");
policy.ExposedHeaders.Add(UserContext.Key);
return policy;
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
CorsPolicy policy = CreateCorsPolicy();
return Task.FromResult(policy);
}
}
然后在注册中:
public static void Register(HttpConfiguration config)
{
config.EnableCors(new IkCorsPolicyProvider());
.....
// rest of the implementation (Routes, etc...)
}
【问题讨论】:
标签: angular asp.net-web-api cors asp.net-web-api2 response-headers