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

时间:2023-11-23 10:26:32

1.特性方式

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

 using System.Web.Http.Filters;
public class OriginAttribute:ActionFilterAttribute
{
private const string Origin = "Origin";
private const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
private const string OriginHeaderdefault = "*";
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, OriginHeaderdefault);
}
}

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

webapi:

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

MVC:

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

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

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

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

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

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

  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