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)的更多相关文章

  1. 跨域资源共享CORS与JSONP

    同源策略限制: 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果没有同源策略,攻击者可以通过JavaScript获取你的邮件以及其他敏感信息,比如说 ...

  2. 跨域资源共享(CORS)问题解决方案

    CORS:Cross-Origin Resource Sharing(跨域资源共享) CORS被浏览器支持的版本情况如下:Chrome 3+.IE 8+.Firefox 3.5+.Opera 12+. ...

  3. VUE SpringCloud 跨域资源共享 CORS 详解

    VUE  SpringCloud 跨域资源共享 CORS 详解 作者:  张艳涛 日期: 2020年7月28日 本篇文章主要参考:阮一峰的网络日志 » 首页 » 档案 --跨域资源共享 CORS 详解 ...

  4. 网络编程-跨域资源共享 CORS

    目录 1.什么是同源策略? 2.跨域资源共享 CORS 3.预检请求 4.CORS相关字段 5.Golang实现跨域 6.参考资料 1.什么是同源策略? 如果两个 URL 的 protocol.por ...

  5. 在Angular.js中的H5页面调用Web api时跨域问题处理

    /// <summary> /// 被请求时 /// 在Angular.js中的H5页面调用Web api时跨域问题处理 /// </summary> /// <para ...

  6. 跨域解决方案 - 跨域资源共享cors

    目录 1. cors 介绍 2. 原理 3. cors 解决跨域 4. 自定义HTTP 头部字段解决跨域 5. 代码演示 5. 参考链接 1. cors 介绍 cors 说的是一个机制,其实相当于一个 ...

  7. 跨域资源共享 CORS 详解(转)

    add by zhj: 公司在一个web产品上,做前后端分离,前后端提供独立的服务,使用不同的域名,通过http进行交互,在 前端,会涉及到跨域访问的问题,前端使用了CORS,后端同时需要做相应修改, ...

  8. Web API 解决跨域问题

    一.跨域问题的由来 同源策略:出于安全考虑,浏览器会限制脚本中发起的跨站请求,浏览器要求JavaScript或Cookie只能访问同域下的内容. 正是由于这个原因,我们不同项目之间的调用就会被浏览器阻 ...

  9. 跨域资源共享 CORS

    CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing). 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从 ...

随机推荐

  1. Elasticsearch 1.4.X 的CORS设置

    最近将Elasticsearch由1.2.2升级到1.4.4后,sense工具无法使用了,它发到Elasticsearch集群的请求没有任何的响应.阅读了Elasticsearch的文档才了解到,这是 ...

  2. STL assign 和swap

    首先看下在整个container上面的复制. c1=c2 可以等同于 c1.erase(c1.begin(),c1.end()) //delete all elems in c1 c1.insert( ...

  3. 安卓开发37:自定义的HorizontalScrollView类,使其pageScroll的时候焦点不选中

    自定义一个HorizontalScrollView类,主要为了让这个HorizontalScrollView不能鼠标点击,不能左右按键,并且没有焦点. public class ImageMoveHo ...

  4. Android:源码环境编译自定义的APP到ROM(System Image)中

    有时候我们需要在源码环境中增加自己的应用或模块,随ROM一起发布. 下面讲述相关步骤: 1. 首先可以在SDK环境下进行编码设计(如果你的APP不涉及到emulator无法模拟的硬件的话) 也可以参考 ...

  5. 静态化 - 伪静态技术(PHP正则表达式实现)

    效果: 代码: <?php // + —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— —— // + 正则表达式,实 ...

  6. 利用VC助手(VA)添加注释

    利用VC助手(VA)添加注释 今天想给自己写的代码加上版权信息,同时整理一下代码的注释.但是为了保持同样的格式,总是copy,显得有些繁琐.然后试图找解决方案.我用的是VS 2010, 刚开始是尝试了 ...

  7. [转][Swust OJ 24]--Max Area(画图分析)

    转载自:http://www.cnblogs.com/hate13/p/4160751.html Max Area 题目描述:(链接:http://acm.swust.edu.cn/problem/2 ...

  8. BZOJ AC300题留念

  9. BZOJ 3713: [PA2014]Iloczyn( 枚举 )

    斐波那契数列<10^9的数很少很少...所以直接暴力枚举就行了... ------------------------------------------------------------- ...

  10. Android:OptionMenu

    MainActivity: package com.example.optionmenu; import android.content.Intent; import android.os.Bundl ...