Asp.Net WebApi服务端解决跨域方案

1.特性方式

 主要是继承ActionFilterAttribute,重写OnActionExecuted方法,在action执行后,给响应头加上一个键值对。

 1 using System.Web.Http.Filters;
 2 public class OriginAttribute:ActionFilterAttribute
 3     {
 4         private const string Origin = "Origin";
 5         private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
 6         private const string OriginHeaderdefault = "*";
 7         public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 8         {
 9             actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, OriginHeaderdefault);
10         }
11     }

这里说下ActionFilterAttribute吧,其实转到定义就很明了的看到了,熟悉ASP.NET MVC的一眼看到的会感觉这不是和MVC中的一样么,其实只是函数个数一样,在MVC中定义的函数分别是OnActionExecuting、OnActionExecuted、OnResultExecuting、OnResultExecuted区别就在这两个

webapi:

MVC:

用法没啥特殊,可以加在Controller上,也可以加载Action上

1        [Origin]
2         public HttpResponseMessage GetProductsALL()
3         {
4             HttpResponseMessage rs = new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(products), System.Text.Encoding.UTF8, "application/json")};
5             return rs;
6         }

2.freamwork(V4.5+)自带的 System.Web.Http.Cors

先在Global.asax.cs文件中配置GlobalConfiguration,然后像加特性一样加载Controller或者Action上

1  public class WebApiApplication : System.Web.HttpApplication
2     {
3         protected void Application_Start()
4         {
5             GlobalConfiguration.Configuration.EnableCors();
6             GlobalConfiguration.Configure(WebApiConfig.Register);
7         }
8     }
1         [EnableCors(origins:"*",headers:"*",methods:"*")]
2        // [Origin]
3         public HttpResponseMessage GetProductsALL()
4         {
5             HttpResponseMessage rs = new HttpResponseMessage() { Content = new StringContent(JsonConvert.SerializeObject(products), System.Text.Encoding.UTF8, "application/json")};
6             return rs;
7         }

  orgins:Comma-separated list of origins that are allowed to access the resource. Use "*" to allow all

      允许访问资源的逗号分隔的源列表。 使用“*”允许所有

  headers

  methods:

      Comma-separated list of headers that are supported by the resource. Use "*" to allow all. Use null or empty string to allow none

      以逗号分隔的资源支持的标题列表。 使用“*”允许所有。 使用null或空字符串不允许

System.Web.Http.Cors介绍的只是冰山一角,系列文章可以访问 http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-05.html

  

原文地址:https://www.cnblogs.com/lb12081116/p/6424871.html