使Web Api 支持跨域资源共享(CORS)
Reference:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Implementation:
1、创建两个项目,WebApi、WebApp,分别是MVC4 Empty、MVC4 Basic项目。
2、在WebApi项目中,添加一个Controller,template选择为Empty API controller

其代码为:
using System.Net.Http;
using System.Web.Http;
namespace WebService.Controllers
{
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
return new HttpResponseMessage()
{
Content = new StringContent("GET: Test message")
};
}
public HttpResponseMessage Post()
{
return new HttpResponseMessage()
{
Content = new StringContent("POST: Test message")
};
}
public HttpResponseMessage Put()
{
return new HttpResponseMessage()
{
Content = new StringContent("PUT: Test message")
};
}
}
}
3、运行WebApi项目,到http://localhost/目录,确保项目正常,如果项目正常,显示为:

4、给WebApp项目添加HomeController,以及Index视图,并给视图添加下面的代码:
<div>
<select id="method">
<option value="get">GET</option>
<option value="post">POST</option>
<option value="put">PUT</option>
</select>
<input type="button" value="Try it" onclick="sendRequest()" />
<span id='value1'>(Result)</span>
</div>
@section scripts {
<script>
var serviceUrl = 'http://myservice.azurewebsites.net/api/test'; // Replace with your URI.
function sendRequest() {
var method = $('#method').val();
$.ajax({
type: method,
url: serviceUrl
}).done(function (data) {
$('#value1').text(data);
}).error(function (jqXHR, textStatus, errorThrown) {
$('#value1').text(jqXHR.responseText || textStatus);
});
}
</script>
}
5、这个时候我们右键WebApp项目——deBug——start new instance,然后点击try按钮,显示的会是Error,因为此时我们的WebApi项目并不支持跨域资源共享如图:

6、这时我们的准备就做好了,现在我们正式开始Implementation,在Nuget的console(打开方式:在VS中,View-other windows-packges manager console)中执行以下命令:
Install-Package Microsoft.AspNet.WebApi.Cors -pre -project WebService(api项目名)
7、在App_Start WebApiConfig中添加如下代码(原来的DefaultApi直接注释掉就行了):
public static void Register(HttpConfiguration config)
{
// New code
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
8、在TestController上添加一个特性EnableCors,如下:
namespace WebService.Controllers
{
[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
9、这个时候我们就已经在WebApi中实现了CORS,你可以用步骤五种的方式,进行测试,得到的结果如下:

Possible ERROR:
在我们从Nuget安装了CORS以后可能会出现以下错误
The type initializer for 'System.Web.Http.GlobalConfiguration' threw an exception
在以下连接中可以找到解决方法:
http://stackoverflow.com/questions/19091195/the-type-initializer-for-system-web-http-globalconfiguration-threw-an-exceptio 在nuget中执行此命令可以解决此错误:Install-Package Microsoft.AspNet.WebApi -IncludePrerelease
使Web Api 支持跨域资源共享(CORS)的更多相关文章
- 跨域资源共享CORS与JSONP
同源策略限制: 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说 ...
- 跨域资源共享(CORS)问题解决方案
CORS:Cross-Origin Resource Sharing(跨域资源共享) CORS被浏览器支持的版本情况如下:Chrome 3+.IE 8+.Firefox 3.5+.Opera 12+. ...
- VUE SpringCloud 跨域资源共享 CORS 详解
VUE SpringCloud 跨域资源共享 CORS 详解 作者: 张艳涛 日期: 2020年7月28日 本篇文章主要参考:阮一峰的网络日志 » 首页 » 档案 --跨域资源共享 CORS 详解 ...
- 网络编程-跨域资源共享 CORS
目录 1.什么是同源策略? 2.跨域资源共享 CORS 3.预检请求 4.CORS相关字段 5.Golang实现跨域 6.参考资料 1.什么是同源策略? 如果两个 URL 的 protocol.por ...
- 在Angular.js中的H5页面调用Web api时跨域问题处理
/// <summary> /// 被请求时 /// 在Angular.js中的H5页面调用Web api时跨域问题处理 /// </summary> /// <para ...
- 跨域解决方案 - 跨域资源共享cors
目录 1. cors 介绍 2. 原理 3. cors 解决跨域 4. 自定义HTTP 头部字段解决跨域 5. 代码演示 5. 参考链接 1. cors 介绍 cors 说的是一个机制,其实相当于一个 ...
- 跨域资源共享 CORS 详解(转)
add by zhj: 公司在一个web产品上,做前后端分离,前后端提供独立的服务,使用不同的域名,通过http进行交互,在 前端,会涉及到跨域访问的问题,前端使用了CORS,后端同时需要做相应修改, ...
- Web API 解决跨域问题
一.跨域问题的由来 同源策略:出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容. 正是由于这个原因,我们不同项目之间的调用就会被浏览器阻 ...
- 跨域资源共享 CORS
CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从 ...
随机推荐
- struts2 DMI问题
最新开始学习struts2,在官网上下载的最新的struts2(2.3.15.2), jar包,在使用动态方法调用的时候老是报错,错误代码如下HTTP Status 404 - There is no ...
- IOS中Key-Value Coding (KVC)的使用具体解释
kvc.键值编码,是一个非正式的协议.它提供一种机制来间接訪问对象的属性. 直接訪问对象是通过调用訪问器的方法实现,而kvc不须要调用訪问器的设置和获取方法.能够直接訪问对象的属性. 以下介绍一下kv ...
- unity学习中经常要碰到的几种数据结构
常碰到的几种数据结构:1.Array,2.ArrayList,3.List<T>,4.LinkedList<T>,5.Queue<T>,6.Stack<T&g ...
- DTM initialization: failure during startup recovery, retry failed, check segment status (cdbtm.c:1603)
安装greenplum集群出现以下错误: 20160315:13:49:16:025696 gpinitsystem:h95:jason-[INFO]:-Checking configuration ...
- android 4.2 root
前一段因工作需要,对android4.2 进行root.但是在下载了 点击打开链接,下载了Superuser.apk,把对应的apk拷贝到system/app,su拷贝到/system/bin 与/s ...
- Jquery中$.ajax()方法参数详解(转)
转自:http://blog.sina.com.cn/doctor830619 url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数, ...
- 安装uwsgi
apt-get install uwsgi uwsgi-plugin-python
- Java字节码中的方法调用
invokestatic,用于static修饰的方法.任何时候调用的时候只需要类名+方法名即可,无需new.JVM直接将其映射到方法区,执行速度极快.当该方法需要参数的时候,invokestatic会 ...
- HDU 3974 Assign the task 简单搜索
根据Rex 的思路才知道可以这么写. 题目意思还是很好理解的,就是找到当前雇员最近的任务. 做法是,可以开辟一个 tim 变量,每次有雇员得到昕任务时候 ++tim 然后取寻找最近的任务的时候写一个搜 ...
- QuartusII 中采用门级原语
QuartusII 中采用门级原语 默认的是前面第一个 为output 后面所有信号为输入 图中的工程实现的是 一个二选一多路选择器