我有一个简单的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);

当前回答

使主答案工作在MVC 5。

使用System.Web.Mvc而不是System.Web.Http.Filters。

using System;
using System.Web.Mvc;
// using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
   ...
}

其他回答

如果您正在使用IIS 7+,您可以放置一个web。配置文件到根文件夹与此在系统中。网络服务器:

<httpProtocol>
   <customHeaders>
      <clear />
      <add name="Access-Control-Allow-Origin" value="*" />
   </customHeaders>
</httpProtocol>

参见:http://msdn.microsoft.com/en-us/library/ms178685.aspx 和http://enable-cors.org/ # how-iis7

这非常简单,只需将其添加到web.config中

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="http://localhost" />
      <add name="Access-Control-Allow-Headers" value="X-AspNet-Version,X-Powered-By,Date,Server,Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Content-Length,Content-Type,Host,Origin,Pragma,Referer,User-Agent" />
      <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
      <add name="Access-Control-Max-Age" value="1000" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

在Origin中输入所有可以访问你的网络服务器的域名, 在header中放入任何ajax HTTP请求可以使用的所有可能的header, 在方法中,把你允许的所有方法放在你的服务器上

的问候:)

如果您正在使用API,请将这一行添加到您的方法中。

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 

使主答案工作在MVC 5。

使用System.Web.Mvc而不是System.Web.Http.Filters。

using System;
using System.Web.Mvc;
// using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
   ...
}
    public ActionResult ActionName(string ReqParam1, string ReqParam2, string ReqParam3, string ReqParam4)
    {
        this.ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
         /*
                --Your code goes here --
         */
        return Json(new { ReturnData= "Data to be returned", Success=true }, JsonRequestBehavior.AllowGet);
    }