json 在 ASP.Net MVC 中设置 Access-Control-Allow-Origin - 最简单的方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6290053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:52:55  来源:igfitidea点击:

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

jsonasp.net-mvc-3corsasp.net-ajax

提问by Kjensen

I have a simple actionmethod, that returns some json. It runs on ajax.example.com. I need to access this from another site someothersite.com.

我有一个简单的 actionmethod,它返回一些 json。它在 ajax.example.com 上运行。我需要从另一个站点 someothersite.com 访问它。

If I try to call it, I get the expected...:

如果我尝试调用它,我会得到预期的...:

Origin http://someothersite.com is not allowed by Access-Control-Allow-Origin.

I know of two ways to get around this: JSONPand creating a custom HttpHandlerto set the header.

我知道有两种方法可以解决这个问题:JSONP和创建自定义 HttpHandler来设置标头。

Is there no simpler way?

没有更简单的方法吗?

Is it not possible for a simple action to either define a list of allowed origins - or simple allow everyone? Maybe an action filter?

一个简单的动作是否不可能定义一个允许来源的列表——或者简单地允许每个人?也许是动作过滤器?

Optimal would be...:

最佳将是...:

return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe);

回答by jgauffin

For plain ASP.NET MVC Controllers

对于普通的 ASP.NET MVC 控制器

Create a new attribute

创建新属性

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

Tag your action:

标记您的操作:

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

For ASP.NET Web API

对于 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);
    }
}

Tag a whole API controller:

标记整个 API 控制器:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

或单独的 API 调用:

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

For Internet Explorer <= v9

对于 Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

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

Download it using nuget corsproxyand follow the included instructions.

使用 nuget 下载它corsproxy并按照包含的说明进行操作。

Blog post| Source code

博客文章| 源代码

回答by LaundroMatt

If you are using IIS 7+, you can place a web.config file into the root of the folder with this in the system.webServer section:

如果您使用的是 IIS 7+,您可以在 system.webServer 部分将 web.config 文件放入文件夹的根目录中:

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

See: http://msdn.microsoft.com/en-us/library/ms178685.aspxAnd: http://enable-cors.org/#how-iis7

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

回答by Ken Smith

I ran into a problem where the browser refused to serve up content that it had retrieved when the request passed in cookies (e.g., the xhr had its withCredentials=true), and the site had Access-Control-Allow-Originset to *. (The error in Chrome was, "Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.")

我遇到了一个问题,当请求传入 cookie(例如,xhr 有它的withCredentials=true)时,浏览器拒绝提供它检索到的内容,并且站点已Access-Control-Allow-Origin设置为*. (Chrome 中的错误是“当凭据标志为真时,无法在 Access-Control-Allow-Origin 中使用通配符。”)

Building on the answer from @jgauffin, I created this, which is basically a way of working around that particular browser security check, so caveat emptor.

基于@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);
    }
}

回答by Zvonimir Tokic

This is really simple , just add this in web.config

这真的很简单,只需在 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>

In Origin put all domains that have access to your web server, in headers put all possible headers that any ajax http request can use, in methods put all methods that you allow on your server

在 Origin 中放置所有可以访问您的 Web 服务器的域,在标头中放置任何 ajax http 请求可以使用的所有可能的标头,在方法中放置您在服务器上允许的所有方法

regards :)

问候 :)

回答by Bishoy Hanna

Sometimes OPTIONS verb as well causes problems

有时 OPTIONS 动词也会引起问题

Simply: Update your web.config with the following

简单:使用以下内容更新您的 web.config

<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>

And update the webservice/controller headers with httpGet and httpOptions

并使用 httpGet 和 httpOptions 更新 webservice/controller 标头

// GET api/Master/Sync/?version=12121
        [HttpGet][HttpOptions]
        public dynamic Sync(string version) 
        {

回答by Tarun

WebAPI 2 now has a package for CORS which can be installed using : Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

WebAPI 2 现在有一个 CORS 包,可以使用以下命令安装Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebServic

Once this is installed, follow this for the code :http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

安装完成后,请按照以下代码获取:http: //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

回答by GrandMasterFlush

This tutorialis very useful. To give a quick summary:

本教程非常有用。快速总结一下:

  1. Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors

  2. In your WebApiConfig.csfile, add config.EnableCors()to the Register()method.

  3. Add an attribute to the controllers you need to handle cors:

  1. 使用 Nuget 上提供的 CORS 包: Install-Package Microsoft.AspNet.WebApi.Cors

  2. 在您的WebApiConfig.cs文件中,添加config.EnableCors()Register()方法。

  3. 为您需要处理 cors 的控制器添加一个属性:

[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]

回答by Gopichandar

Add this line to your method, If you are using a API.

将此行添加到您的方法中,如果您使用的是 API。

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

回答by Pranav Labhe

    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);
    }

回答by Trilok Pathak

There are different ways we can pass the Access-Control-Expose-Headers.

我们可以通过不同的方式传递 Access-Control-Expose-Headers。

  • As jgauffin has explained we can create a new attribute.
  • As LaundroMatt has explained we can add in the web.config file.
  • Another way is we can add code as below in the webApiconfig.cs file.

    config.EnableCors(new EnableCorsAttribute("", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

  • 正如 jgauffin 所解释的,我们可以创建一个新属性。
  • 正如 LaundroMatt 所解释的,我们可以添加 web.config 文件。
  • 另一种方法是我们可以在 webApiconfig.cs 文件中添加如下代码。

    config.EnableCors(new EnableCorsAttribute(" ", headers: "", methods: "*",exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });

Or we can add below code in the Global.Asax file.

或者我们可以在 Global.Asax 文件中添加以下代码。

protected void Application_BeginRequest()
        {
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                //These headers are handling the "pre-flight" OPTIONS call sent by the browser
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "*");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost:4200");
                HttpContext.Current.Response.AddHeader("Access-Control-Expose-Headers", "TestHeaderToExpose");
                HttpContext.Current.Response.End();
            }
        }

I have written it for the options. Please modify the same as per your need.

我已经为选项编写了它。请根据您的需要修改相同的内容。

Happy Coding !!

快乐编码!!