我有一个简单的actionmethod,它返回一些json。它在ajax.example.com上运行。我需要从另一个网站someothersite.com访问这个。
如果我尝试调用它,我会得到预期的…:
Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin.
我知道有两种方法可以解决这个问题:JSONP和创建一个自定义HttpHandler
设置标题。
有没有更简单的办法?
对于一个简单的操作来说,是否不可能定义一个允许起源的列表-或者简单地允许所有人?也许是一个动作过滤器?
最理想的是……
return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe);
有时OPTIONS动词也会引起问题
简单:
更新你的网页。配置如下
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
用httpGet和httpOptions更新webservice/controller头
// GET api/Master/Sync/?version=12121
[HttpGet][HttpOptions]
public dynamic Sync(string version)
{
我遇到了一个问题,当请求传入cookie时,浏览器拒绝提供它已经检索到的内容(例如,xhr有它的withCredentials=true),并且站点有Access-Control-Allow-Origin设置为*。(Chrome中的错误是,“当凭据标志为真时,不能在Access-Control-Allow-Origin中使用通配符。”)
基于@jgauffin的回答,我创建了这个,这基本上是一种绕过特定浏览器安全检查的方法,所以买者自负。
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// We'd normally just use "*" for the allow-origin header,
// but Chrome (and perhaps others) won't allow you to use authentication if
// the header is set to "*".
// TODO: Check elsewhere to see if the origin is actually on the list of trusted domains.
var ctx = filterContext.RequestContext.HttpContext;
var origin = ctx.Request.Headers["Origin"];
var allowOrigin = !string.IsNullOrWhiteSpace(origin) ? origin : "*";
ctx.Response.AddHeader("Access-Control-Allow-Origin", allowOrigin);
ctx.Response.AddHeader("Access-Control-Allow-Headers", "*");
ctx.Response.AddHeader("Access-Control-Allow-Credentials", "true");
base.OnActionExecuting(filterContext);
}
}