Asp.Net WebApi服务端解决跨域方案
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:
MVC:
用法没啥特殊,可以加在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
最新文章
- 【转】在CentOS6.5安装 svn1.8 (亲测可用)
- [LeetCode] Mini Parser 迷你解析器
- sqlserver总结-视图及存储过程
- SQL多表查询:内连接、外连接(左连接、右连接)、全连接、交叉连接
- easyui源码翻译1.32--DateTimeBox(日期时间输入框)
- Android开发之显示通知
- c# 使用OracleParameter,同时使用replace函数
- Nginx之旅系列 - Nginx的configuration
- C++数据结构之map----第一篇
- PipedInputStream和PipedOutputStream详解
- 【前端单元测试入门05】react的单元测试之jest
- HTML DOCTYPE 的重要性
- 【感悟】一次不太好的寻找bug的体验,RecyclerView
- 阿里云,未找到或无法访问服务器.请验证实例名称是否正确并且 SQL Server 已配置为允许远程连接.
- zabbix使用自定义脚本监控内存
- Oracle查看表或者视图的定义语句
- 插入图片新方式:data:image
- Ajax—web中ajax的常用方式
- mysql主从复制——双机互为主从
- oracle 3大范式 理解
热门文章
- VMware vCenter Server安装与配置
- ZCMU Problem A: Good Joke!
- Centos6.5安装mysql5.7详解
- 【dfs序】【set】bzoj3991 [Sdoi2015]寻宝游戏
- 更新升级10.11 cocoapods安装出问题最简单的解决方法
- Ghost下的gho镜像分区工具
- Java中泛型得到T.class
- 网络抓包工具Wireshark和Fidder
- Linux下打包命令tar
- 【mybatis】mybatis使用java实体中定义的常量,或静态方法