使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请求,从 ...
随机推荐
- jquery选择器控制Html元素
1.JQuery中有addClass,removeClass,toggleClass addClass(class):为每个匹配的元素添加指定的类名 removeClass(class):从所有匹配的 ...
- MFC技术内幕系列之(四)---MFC消息映射与消息传递内幕
//////////////////////////////////////////////////////////////////////////////////// ...
- 【Oracle】nvl与nvl2对比
1.nvl(v1,v2),只要v1为null,即将值变为v2. pay(类型):number; 在执行 nvl(pay_type,'null') 函数的时候会提示无效数字,可能是nvl函数会自动将其转 ...
- Markdown 11 种基础语法
现在是我在学习Markdown时做的笔记.学完这些Markdown的基本使用已经不成问题. 1. 标题设置(让字体变大,和word的标题意思一样)在Markdown当中设置标题,有两种方式: 第一种: ...
- Jquery中$.ajax()方法参数详解(转)
转自:http://blog.sina.com.cn/doctor830619 url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. type: 要求为String类型的参数, ...
- Python 模块(五)
目录 模块介绍 time &datetime模块 random json & picle 一.模块介绍 在我们日常的程序开发过程中,随着代码越写越多,在单个文件里的代码就会越来越长,越 ...
- tomcat虚拟主机虚拟目录配置
今天着实要记上一笔,需要配置tomcat虚拟目录的问题 一 首先看两个名词 appBase -- 顾名思义 就是你app所在的目录,目录下面的子目录将自动被部署为应用:war被解压并部署 docBas ...
- (Problem 13)Large sum
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers. 371072875339 ...
- QT5.6所开放的7个新模块(图表,虚拟键盘,性能分析,静态分析,测试正好,2D渲染)
The modules newly available to open source users are: Qt Charts Qt Data Visualization Qt Virtual Key ...
- 基于visual Studio2013解决算法导论之015第二小元素
题目 查找第二小元素 解决代码及点评 #include <stdio.h> #include <stdlib.h> #include <malloc.h> ...