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

当前回答

我正在使用DotNet核心MVC,在与nuget包、Startup.cs、属性和这个地方战斗了几个小时后,我简单地将这个添加到MVC动作中:

Response.Headers.Add("Access-Control-Allow-Origin", "*");

我知道这是相当笨拙的,但这是我所需要的,没有其他想要添加这些头文件。我希望这能帮助到其他人!

其他回答

对于普通ASP。NET MVC控制器

创建一个新属性

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

标记你的行动:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

ASP。NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

标记整个API控制器:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

或者单独的API调用:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

对于Internet Explorer <= v9

IE <= 9不支持CORS。我已经写了一个javascript,将自动路由这些请求通过代理。这一切都是100%透明的(你只需要包括我的代理和脚本)。

使用nuget corsproxy下载它,并遵循附带的说明。

博客文章|源代码

After struggling for a whole evening I finally got this to work. After some debugging I found the problem I was walking into was that my client was sending a so called preflight Options request to check if the application was allowed to send a post request with the origin, methods and headers provided. I didn't want to use Owin or an APIController, so I started digging and came up with the following solution with just an ActionFilterAttribute. Especially the "Access-Control-Allow-Headers" part is very important, as the headers mentioned there do have to match the headers your request will send.

using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyNamespace
{
    public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            // check for preflight request
            if (request.Headers.AllKeys.Contains("Origin") && request.HttpMethod == "OPTIONS")
            {
                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                response.End();
            }
            else
            {
                HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                HttpContext.Current.Response.Cache.SetNoStore();

                response.AppendHeader("Access-Control-Allow-Origin", "*");
                response.AppendHeader("Access-Control-Allow-Credentials", "true");
                if (request.HttpMethod == "POST")
                {
                    response.AppendHeader("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
                    response.AppendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, X-RequestDigest, Cache-Control, Content-Type, Accept, Access-Control-Allow-Origin, Session, odata-version");
                }

                base.OnActionExecuting(filterContext);
            }
        }
    }
}

最后,我的MVC动作方法看起来像这样。这里重要的是还要提到Options HttpVerbs,否则preflight请求将失败。

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Options)]
[AllowCrossSiteJson]
public async Task<ActionResult> Create(MyModel model)
{
    return Json(await DoSomething(model));
}

使主答案工作在MVC 5。

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

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

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
   ...
}

在网络上。输入以下命令

<system.webServer>
<httpProtocol>
  <customHeaders>
    <clear />     
    <add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Allow-Origin" value="http://localhost:123456(etc)" />
  </customHeaders>
</httpProtocol>

有时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) 
        {