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

问题描述

我有一个MVC项目,其中我有几个JSON控制器方法我想暴露跨域。不是整个网站,只是这两种方法。

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:

但是,问题是我有一个常规的MVC项目,而不是一个WEB API,意思是,我不能按照注册寄存器的步骤

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项目中。

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

推荐答案

如下所述:

您应该创建一个操作过滤器并在其中设置标题。您可以对任何所需的操作方法使用此操作过滤器。

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

如果要添加多个域, t只是多次设置标题。在您的操作过滤器中,您需要检查请求的域是否来自您的域列表,然后设置标题。

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 07:01
查看更多