一、客户端用JSONP请求数据

如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的:

{"YourSignature": "嫁人要嫁程序员,钱多话少死得早"}

然而,JSONP请求期望得到这样的JSON:

jQuery123456({"YourSignature": "嫁人要嫁程序员,钱多话少死得早"})

所以我们需要对WebAPI做拓展,让它支持这样的callback。我找到了两种办法。

自己写个Attribute,来给返回的JSON包上callback

public class JsonCallbackAttribute : ActionFilterAttribute
{
private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext context)
{
var callback = string.Empty; if (IsJsonp(out callback))
{
var jsonBuilder = new StringBuilder(callback);
jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
context.Response.Content = new StringContent(jsonBuilder.ToString());
}
base.OnActionExecuted(context);
} private bool IsJsonp(out string callback)
{
callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];
return !string.IsNullOrEmpty(callback);
}
}

然后在要被调用的方法前加上这个Attribute:

        [JsonCallback]
[HttpGet]
public HttpResponseMessage a()
{
string strJson = "{\"info\" : \"true\"}";
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(strJson, Encoding.UTF8, "text/plain")
};
return result;
}

非常简洁明了,但是这种方法有个缺点,就是被加了[JsonCallback]的方法,只能适用于JSONP的请求。如果你希望API能被各种场合的客户端调用,还是在服务端提供支持吧。

2. 通过自定义JsonMediaTypeFormatter实现

参见 Artech大神的文章:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html

蒋大神的文章的JsonpMediaTypeFormatter类只适合将对象传过去进行json序列化,有点弊端

支持CORS最地道的方法当然是在服务端提供支持,按官网的办法,100%成功。http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

主要步骤是:

1. 到nuget上装一个包:http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Cors/

2. 在WebApiConfig.Register方法中加入代码:

config.EnableCors();

3. 在Controller上加上Attribute:

[EnableCors(origins: "http://myclient.azurewebsites.net", headers: "*", methods: "*")]

这个域名是可以配置的,具体还请参考上面给出的官网教程。

最后,还要告诉大家一个坑,在服务端完提供支持以后,不要高兴的太早,如果你用jQuery.ajax()的方式去请求,还是会爆的:

$.ajax({
url: 'yourCORSurl',
data: '',
dataType: 'json',
type: 'GET',
contentType: 'application/json; charset=utf-8',
...
})

经过无数次爆破,终于发现,只要把dataType和contentType两个参数去掉,就肯定不会爆了!!!

ASP.NET Web API 跨域访问(CORS)要注意的地方的更多相关文章

  1. ASP.NET Web API 跨域访问(CORS)

    一.客户端用JSONP请求数据 如果你想用JSONP来获得跨域的数据,WebAPI本身是不支持javascript的callback的,它返回的JSON是这样的: {"YourSignatu ...

  2. ASP.NET Web API 跨域访问

    自定义特性 要在WebApi中实现JSONP,一种方式是实现自定义特性  http://stackoverflow.com/questions/9421312/jsonp-with-asp-net-w ...

  3. Web Api跨域访问配置及调用示例

    1.Web Api跨域访问配置. 在Web.config中的system.webServer内添加以下代码: <httpProtocol> <customHeaders> &l ...

  4. Web API 跨域访问(CORS)

    1.在web.config里把“    <remove name="OPTIONSVerbHandler" />  ”删掉. 2. 到nuget上装一个包:    ht ...

  5. asp.net web api 跨域问题

    缘起 以前在asp.net mvc时代,很少出现跨域问题 自从使用了asp.net web api + angular (1/2)之后,开始有跨域问题了. 简单普及下跨域: 我的理解是只要是前台页面与 ...

  6. asp.net web api 跨域,带cookie

    官网上有一个介绍 http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api 但是只支 ...

  7. ASP.NET web api 跨域请求

    1.学习文章:AJAX 跨域请求 - JSONP获取JSON数据 1.asp.net代码 参考文章:http://www.sxt.cn/info-2790-u-756.html (1).增加CorsH ...

  8. ASP.Net开发WebAPI跨域访问(CORS)的精简流程

    1: Web.config里有一行: <remove name="OPTIONSVerbHandler" /> 这个要删除. 2: nuget安装Microsoft.A ...

  9. web api 跨域访问

    在工程中 Install-Package Microsoft.AspNet.WebApi.Cors 在 webapiconfig.cs中 config.EnableCors(); 在 控制器中, [E ...

随机推荐

  1. Redis笔记(二):Redis数据类型

    Redis 数据类型 Redis支持五种数据类型:string(字符串),hash(哈希),list(列表),set(集合)及zset(sorted set:有序集合). String(字符串) st ...

  2. Integer.parseInt() 和 valueOf()

    parseInt("1")返回的是int类型,所以如果想要将一个String类型的数字串转为原始类型int ,建议使用这个方法, 而不是使用 valueOf("1&quo ...

  3. lucene源码分析(2)读取过程实例

    1.官方提供的代码demo Analyzer analyzer = new StandardAnalyzer(); // Store the index in memory: Directory di ...

  4. shell:syntax error:unexpected end of file/Starting proxy www-balancer: cannot bind socket--转载

    src:http://www.2cto.com/os/201308/238962.html   执行某bash脚本是发生: syntax error: unexpected end of file 主 ...

  5. 安装和使用mongodb

    环境: Ubuntu 13.04 安装MongoDB $sudo apt-get install mongodb 会自动安装libpcrecpp0 libboost-system1.42.0 libb ...

  6. SQLite菜鸟教程

    学习链接:http://www.runoob.com/sqlite/sqlite-trigger.html

  7. c#基础学习(0703)之string.Format格式化日期

    C# string.Format格式化日期 DateTime dt = ,,,,,,); string.Format("{0:y yy yyy yyyy}",dt); //17 1 ...

  8. Javascript一个在页面内追加元素的小例子

    如下: <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8 ...

  9. 什么是memcached?

    缓存是一种常驻与内存的内存数据库,内存的读取速度远远快于程序在磁盘读取数据的速度.我们在设计程序的时候常常会考虑使用缓存,将经常访问的数据放到内存上面这样可以提高访问数据的速度,同时可以降低磁盘或数据 ...

  10. videojs IE8无法播放解决方案

    1.如果是在.cs文件里初始化视频元素,没有遇到无法播放问题. 2.如果是js动态换播放器的poster和src遇到此问题,解决办法是用videojs提供的函数来设置 https://github.c ...