在ASP .NET MVC5 CORS [英] CORS in ASP .NET MVC5

查看:2042
本文介绍了在ASP .NET MVC5 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我有一对夫妇的JSON控制器方法我要揭露跨域一个MVC项目。而不是整个网站,只是这两种方法。

I have a MVC project in which I have a couple of JSON controller methods I want to expose cross domain. Not the entire site, just these two methods.

我基本上要在这个职位CORS规定的确切的事情:

I basically want to to the exact thing stated in this post for cors:

http://enable-cors.org/server_aspnet.html

然而,问题是,我有一个定期的MVC项目,而不是一个WEB API,这意味着,我不能跟着regaring寄存器中的步骤

However, the problem is that I have a regular MVC project and not a WEB API, meaning, that I cannot follow the steps regaring the register

public static void Register(HttpConfiguration config)
{
    // New code
    config.EnableCors();
}

,因为它的方法是不是在我的MVC项目present。

method since it is not present in my MVC project.

有没有使用这个库,尽管它是一个MVC项目的方式?

Is there a way to use this library although it is a MVC project?

我所知道的,我可以用通过的web.config配置是:

I'm aware of that I can config this through web.config using:

<httpProtocol>
      <customHeaders>
        <clear />
        <add name="Access-Control-Allow-Origin" value="http://www.domain.com" />
      </customHeaders>
</httpProtocol>

但我不希望公开所有方法,我要指定一个域(2域)更能够获得我的方法...

But I don't want to expose all methods, and I want to specify more than one domain (2 domains) to have access to my methods...

推荐答案

作为描述如下:<一href=\"http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method\">Setting访问控制允许来源在ASP.Net MVC - 最简单可行的方法

您应该只创建一个动作过滤器,并设置有头。无论你想,你可以在你的操作方法使用此动作过滤器。

You should just create an action filter and set the headers there. You can use this action filter on your action methods wherever you want.

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

如果您要添加多个域,你不能只设置页眉多次。在你的行动过滤器,你需要检查,如果请求的域名是从域列表,然后设置标题。

If you want to add multiple domains, you can't just set the header multiple times. In your action filter you will need to check if the requesting domain is from your list of domains and then set the header.

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var domains = new List<string> {"domain2.com", "domain1.com"};

        if (domains.Contains(filterContext.RequestContext.HttpContext.Request.UrlReferrer.Host))
        {
            filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        }

        base.OnActionExecuting(filterContext);
    }

这篇关于在ASP .NET MVC5 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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