我第一次深入到网站的部署中。我在web控制器中从客户端的角控制器发出交叉起源请求(CORS)。对于开发,我已经在Web控制器上设置了EnableCors属性,但是很明显,它指向了我的本地机器上的一个站点。当我将该设置移动到一个托管的生产站点时,我试图弄清楚如何轻松地转换该设置。
发布于 2016-01-22 03:04:14
为所有域启用CORS
您的第一个选项是为所有域启用CORS。这可能不是最安全的选择,例如,如果您知道您的API将只从预先定义的一组网站(例如,您的角应用程序)访问。但在某些情况下,可以在全球范围内启用CORS。
你可以在WebApiConfig上做
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Enable CORS globally for all routes
var enableCorsAttribute = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(enableCorsAttribute);
// Other configurations
}
}或在配置中启用CORS支持,然后在特定控制器/操作上使用EnableCors属性:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.EnableCors();
// Other configurations
}
}
public class ValuesController : ApiController
{
[HttpGet]
[Route("api/values")]
[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]
public string[] GetValue()
{
}
}从Azure门户启用CORS
如果是Azure中的主机,我认为Web应用程序现在允许您启用CORS支持,并从Azure Portal指定允许的域:

基于应用程序设置启用CORS
另一个选项是为可以从App配置的域启用CORS。通过这种方式,您可以使用web.config转换、部署令牌注入或仅使用Azure更改不同API实例的允许域。通过创建实现ICorsPolicyProvider接口的自己的属性,可以很容易地做到这一点:
// The implementation below supports only a single origin and
// doesn't allow you to specify allowed headers or request types.
// But it can be easily extended to support these scenarios as well.
public class EnableCorsWithConfigAttribute : Attribute, ICorsPolicyProvider
{
private readonly string configKey;
public EnableCorsWithConfigAttribute(string configKey)
{
this.configKey = configKey;
}
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var policy = new CorsPolicy
{
AllowAnyOrigin = false,
AllowAnyHeader = true,
AllowAnyMethod = true,
};
if (ConfigurationManager.AppSettings
.AllKeys
.Contains(configKey))
{
var origin = ConfigurationManager.AppSettings[configKey];
if (!origins.IsNullOrWhitespace())
{
policy.AllowAnyOrigin = origins.Equals("*");
if (!policy.AllowAnyOrigin) policy.Origins.Add(origin);
}
}
return Task.FromResult(policy);
}
}然后您可以按以下方式使用它:
public class ValuesController : ApiController
{
[HttpGet]
[Route("api/values")]
[EnableCorsWithConfig("Application:Cors:AllowedOrigin")]
public string[] GetValue()
{
}
}https://stackoverflow.com/questions/34937575
复制相似问题