前言:因为公司项目需要搭建一个Web API 的后端,用来传输一些数据以及文件,之前有听过Web API的相关说明,但是真正实现的时候,感觉还是需要挺多知识的,正好今天有空,整理一下这周关于解决CORS的问题,让自己理一理相关的知识。

ASP.NET Web API支持CORS方式,据我目前在网上搜索,有两种方式

  • 通过扩展CorsMessageHandle实现:             http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html
  • 通过微软的 AspNet.WebApi.Cors 类库实现  http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#intro

本文主要是利用AspNet.WebApi.Cors 类库实现CORS,因为在选择的过程中,发现扩展的CorsMessageHandle会有一些限制,因为真正项目的HTTP Request 是Rang Request.

你需要了解的一些知识

  • Web API 2.0              http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
  • 同源策略与JSONP     http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-01.html
  • CORS                         http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-02.html

1.创建Web API (myservice.azurewebsites.net)

这个简单放上图:

1.1

1.2

1.3

1.4

1.5

1.6将下面的code替代原来的TestController

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")            };        }    }}

1.7 可以测试创建的Web API是否可以正常工作

2.创建Client端(myclilent.azurewebsites.net)

这也是可以简单上图:

2.1

2.2

2.3 找到 Client端的 Views/Home/Index.cshtml,用下面代码替代

<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>}

2.4用例外一个域名发布网站,然后进入Index 页面,选择 GET,POST,PUT 等,点击 Try it 按钮,就会发送请求到Web API, 因为Web API没有开启CORS,而通过AJAX请求,浏览器会提示 错误

3.Web API支持CORS

3.1打开VS,工具->库程序包管理器->程序包管理器控制台 ,输入下列命令:Install-Package Microsoft.AspNet.WebApi.Cors -Version 5.0.0  

注意 :目前Nuget 上面最新的版本是5.2.0 ,但是我测试,下载的时候,会有一些关联的类库不是最新的,System.Net.Http.Formatting 要求是5.2,我在网上找不带这dll,因此建议安装 :Microsoft.AspNet.WebApi.Cors 5.0就OK了。

Nuget 科普link:    http://www.cnblogs.com/dubing/p/3630434.html

3.2 打开 WebApiConfig.Register 添加 config.EnableCors()

using System.Web.Http;namespace WebService{    public static class WebApiConfig    {        public static void Register(HttpConfiguration config)        {            // New code            config.EnableCors();            config.Routes.MapHttpRoute(                name: "DefaultApi",                routeTemplate: "api/{controller}/{id}",                defaults: new { id = RouteParameter.Optional }            );        }    }}

3.3 添加[EnableCors] 特性 到 TestController

using System.Net.Http;using System.Web.Http;using System.Web.Http.Cors;namespace WebService.Controllers{    [EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]    public class TestController : ApiController    {        // Controller methods not shown...    }}

3.4回到Client端,这时再次发送请求,会提示成功信息,证明CORS已经实现了。

4.为[EnableCors]设置到 Action, Controller, Globally

4.1Action

public class ItemsController : ApiController{    public HttpResponseMessage GetAll() { ... }    [EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]    public HttpResponseMessage GetItem(int id) { ... }    public HttpResponseMessage Post() { ... }    public HttpResponseMessage PutItem(int id) { ... }}

4.2Controller

[EnableCors(origins: "http://www.example.com", headers: "*", methods: "*")]public class ItemsController : ApiController{    public HttpResponseMessage GetAll() { ... }    public HttpResponseMessage GetItem(int id) { ... }    public HttpResponseMessage Post() { ... }    [DisableCors]    public HttpResponseMessage PutItem(int id) { ... }}

4.3Globally

public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        var cors = new EnableCorsAttribute("www.example.com", "*", "*");        config.EnableCors(cors);        // ...    }}

5.[EnableCors]工作原理

要理解CORS成功的原理,我们可以来查看一下

跨域的请求

GET http://myservice.azurewebsites.net/api/test HTTP/1.1Referer: http://myclient.azurewebsites.net/Accept: */*Accept-Language: en-USOrigin: http://myclient.azurewebsites.netAccept-Encoding: gzip, deflateUser-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)Host: myservice.azurewebsites.net

当发送请求的时候,浏览器会将“Origin”的请求头发送给 服务端,如果服务端允许跨域请求,那么响应回来的请求头,添加“Access-Control-Allow-Origin”,以及将请求过来的 域名 的value添加到 Access-Control-Allow-Origin,浏览器接收到这个 请求头,则会显示返回的数据,否则,即使服务端成功返回数据,浏览器也不会接收

服务器的响应

HTTP/1.1 200 OKCache-Control: no-cachePragma: no-cacheContent-Type: text/plain; charset=utf-8Access-Control-Allow-Origin: http://myclient.azurewebsites.netDate: Wed, 05 Jun 2013 06:27:30 GMTContent-Length: 17GET: Test message

6.自定义CORS Policy Providers

6.1除了使用自带的[EnableCors]特性外,我们可以自定义自己的[EnableCors]。首先是要继承Attribute 和 ICorsPolicyProvider 接口

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false)]public class MyCorsPolicyAttribute : Attribute, ICorsPolicyProvider {    private CorsPolicy _policy;    public MyCorsPolicyAttribute()    {        // Create a CORS policy.        _policy = new CorsPolicy        {            AllowAnyMethod = true,            AllowAnyHeader = true        };        // Add allowed origins.        _policy.Origins.Add("http://myclient.azurewebsites.net");        _policy.Origins.Add("http://www.contoso.com");    }    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)    {        return Task.FromResult(_policy);    }}

实现后,可以添加自己定义的[MyCorsPolicy]

[MyCorsPolicy]public class TestController : ApiController{    .. //

6.2或者你也可以从配置文件中读取 允许的域名

public class CorsPolicyFactory : ICorsPolicyProviderFactory{    ICorsPolicyProvider _provider = new MyCorsPolicyProvider();    public ICorsPolicyProvider GetCorsPolicyProvider(HttpRequestMessage request)    {        return _provider;    }} public static class WebApiConfig{    public static void Register(HttpConfiguration config)    {        config.SetCorsPolicyProviderFactory(new CorsPolicyFactory());        config.EnableCors();        // ...    }}
 
 http://www.th7.cn/Program/net/201407/234213.shtml

通过微软的cors类库,让ASP.NET Web API 支持 CORS的更多相关文章

  1. 通过扩展让ASP.NET Web API支持W3C的CORS规范

    让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...

  2. 跨域资源共享(CORS)在ASP.NET Web API中是如何实现的?

    在<通过扩展让ASP.NET Web API支持W3C的CORS规范>中,我们通过自定义的HttpMessageHandler自行为ASP.NET Web API实现了针对CORS的支持, ...

  3. 通过扩展让ASP.NET Web API支持JSONP

    同源策略(Same Origin Policy)的存在导致了"源"自A的脚本只能操作"同源"页面的DOM,"跨源"操作来源于B的页面将会被拒 ...

  4. (转)通过扩展让ASP.NET Web API支持JSONP

    原文地址:http://www.cnblogs.com/artech/p/3460544.html 同源策略(Same Origin Policy)的存在导致了“源”自A的脚本只能操作“同源”页面的D ...

  5. 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示

    随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细.比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑.注意,这里是 ...

  6. 通过扩展让ASP.NET Web API支持W3C的CORS规范(转载)

    转载地址:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html CORS(Cross-Origin Resource Shari ...

  7. CORS support for ASP.NET Web API (转载)

    CORS support for ASP.NET Web API Overview Cross-origin resource sharing (CORS) is a standard that al ...

  8. 让ASP.NET Web API支持POST纯文本格式(text/plain)的数据

    今天在web api中遇到了这样一个问题,虽然api的参数类型是string,但只能接收post body中json格式的string,不能接收原始string. web api是这样定义的: pub ...

  9. 让ASP.NET Web API支持$format参数的方法

    在不使用OData的情况下,也可以让ASP.NET Web API支持$format参数,只要在WebApiConfig里添加如下三行红色粗体代码即可: using System; using Sys ...

随机推荐

  1. LOB字段存放在指定表空间 清理CLOB字段及压缩CLOB空间

     LOB字段存放在指定表空间 清理CLOB字段及压缩CLOB空间    把LOB字段的SEGMENT 存放在指定表空间.清理CLOB字段及压缩CLOB空间 1.创建LOB字段存放表空间:create ...

  2. Windows调试学习笔记:(二)WinDBG调试.NET程序示例

    好不容易把环境打好了,一定要试试牛刀.我创建了一个极其简单的程序(如下).让我们期待会有好的结果吧,阿门! using System; using System.Collections.Generic ...

  3. Android NDK 同时编译多个Module

    LOCAL_PATH := $(call my-dir) ## ## NDK 支持同时编译多个Module: ## 在配置的时候,每个Module需要 以 include $(CLEAR_VARS)开 ...

  4. android studio 翻译插件

    插件下载地址 https://github.com/Skykai521/ECTranslation/releases 使用说明: http://gold.xitu.io/entry/573d8d92a ...

  5. ch4 MySQL 安全管理

    第 4 章 MySQL 安全管理 前言 对于任何一个企业来说,其数据库系统中所保存数据的安全性无疑是非常重要的,尤其是公司的有些商业数据,可能数据就是公司的根本,失去了数据的安全性,可能就是失去了公司 ...

  6. 使用python pylab库 画线

    pylab 提供了比较强大的画图功能,但是函数和参数都比较多,很容易搞混.我们平常使用最多的应该是画线了.下面,简单的对一些常用的划线函数进行了封装,方便使用. # -*- coding: utf-8 ...

  7. httpwebrequest 服务器提交了协议冲突. section=responsestatusline

    调用接口的时候,包: httpwebrequest 服务器提交了协议冲突. section=responsestatusline 解决方案: req.KeepAlive = false; req.Al ...

  8. redis的主从复制部署和使用

    reids一种key-value的缓存数据库目前非常流行的被使用在很多场景,比如在数据库读写遇到瓶颈时缓存且读写分离会大大提升这块的性能,下面我就说说redis的主从复制 首先需要启动多个redis实 ...

  9. 使用PowerDesigner导出Word/HTML的一些配置

    目标:根据物理视图导出代码和列清单(包括字段.类型.注释).由于默认导出的要素太多,大多不是自己想要的,这里简单说下导出目标的一些配置,留下来备用. 其中,Title中的图和Table表格中的代码预览 ...

  10. C++ Low level performance optimize

    C++ Low level performance optimize 1.  May I have 1 bit ? 下面两段代码,哪一个占用空间更少,那个速度更快?思考10秒再继续往下看:) //v1 ...