在 ASP.Net MVC 中设置 Access-Control-Allow-Origin - 最简单的方法 [英] Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

查看:33
本文介绍了在 ASP.Net MVC 中设置 Access-Control-Allow-Origin - 最简单的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

我知道有两种方法可以解决这个问题:JSONP 并创建一个 自定义 HttpHandler到设置标题.

I know of two ways to get around this: JSONP and creating a custom HttpHandler to set the header.

没有更简单的方法吗?

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

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

最佳选择是...:

return json(mydata, JsonBehaviour.IDontCareWhoAccessesMe);

推荐答案

对于普通的 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% 透明的(你只需要包括我的代理和脚本).

For 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).

使用 nuget corsproxy 下载并按照附带的说明进行操作.

Download it using nuget corsproxy and follow the included instructions.

博文 |源代码

这篇关于在 ASP.Net MVC 中设置 Access-Control-Allow-Origin - 最简单的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆