使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请求,从 ...
随机推荐
- 解决虚拟内存不够导致Eclipse is not responding
安装目录下eclipse.ini中: 修改参数至必要大小. e.g. -vmargs-Djava.net.preferIPv4Stack=true-Dosgi.requiredJavaVersion= ...
- 查看Oracle有哪些表或者视图
转自:http://www.2cto.com/database/201211/167577.html 1.查询当前用户下,有哪些表 Sql代码 SELECT * FROM user_tables ...
- 一个分组查询 每组前 10 的sql 语句
USE tmpgo CREATE TABLE Employee( ID int identity(1,1), EmpName varchar(20), EmpSalary varchar(10), E ...
- [javascript]MooTools Selectors(MooTools 选择器) ELEMENT DOM选择
//ELEMENT DOM选择//on are tag names. //All the divs on the page: $$('div'); //All the divs and paragra ...
- javascript 关闭页面提示
window.onbeforeunload = function (e) { e = e || window.event; // For IE and Firefox prior to version ...
- 查询sql语句耗时的方法!
declare @times datetimeset @times=getdate()--要查询的sql语句select [注册数花费时间(毫秒)]=datediff(ms,@times,getdat ...
- [转] HTC:html组件
~~~不时会看到 用htc实现 hover, border-raius等效果,可以用来弥补IE6-8的不足.那么htc到底是什么呢? 1.摘要 本文在实例的基础上讨论了HTC(HTML Compone ...
- Log4J logger图片
- PHP - 抓取电视剧资源
<?php /** * 获取下载url * @return [type] [description] */ function getVedioDwonloadUrl() { for ($i=1; ...
- main函数的参数问题 (转载)
void main(int arg ,char *arv[]){} arg -- 命令行参数总个数arv[0] -- 参数1,程序名 arv[1] -- 参数2,字符串 arv[2] -- 参数3,字 ...