$.ajax 跨域请求 Web Api

时间:2022-06-25 01:06:07

WepApi确实方便好用,没有配置文件,一个apicontroller直接可以干活了。但今天用$.ajax跨域请求的时候总是获取不到数据,用fiddler一看确实抓到了数据,但回到$.ajax函数中,直接触发了error,没有触发success,即使状态码是200。用apiclient或者浏览器直接访问都是ok的。搜罗一番。最终在这篇文章上面找到答案 。http://code.msdn.microsoft.com/windowsdesktop/Implementing-CORS-support-a677ab5d

原因

在默认情况下,为防止CSRF跨站伪造攻击,一个网页从另外一个域的网页获取数据的时候就会受到限制。有一些方法可以突破这个限制,JSONP就是其一。它使用<script> 标签加一个回调函数。但JSONP 只支持Get方法。而CORS(Cross-Origin Resource Sharing) 跨域资源共享,是一种新的header规范,可以让服务器端放松跨域的限制,可以根据header来切换限制或不限制跨域请求。它支持所有的Http请求方式。跨域的资源请求带有一个Http header:Origin,如果服务器支持CORS,响应就会带有一个header:Access-Control-Allow-Origin ,也有一些特殊的请求。采用 HTTP “OPTIONS” 的方式,hearder中带有Access-Control-Request-Method或Access-Control-Request-Headers,服务器响应的hearder中需要带有Access-Control-Allow-Methods,Access-Control-Allow-Headers才行。

实现

那怎么实现CORS呢,这用到了Message Handler。它可以在管道中拦截并修改Request,代码如下:

 public class CorsHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers"; protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew<HttpResponseMessage>(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First()); string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
} string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
} return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}

然后在Global中加入:

 protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
WebApiConfig.Register(GlobalConfiguration.Configuration);
}

脚本:

  $.ajax({
// url: "http://localhost:11576/api/Values",
url: "http://localhost:39959/api/user/login?name=niqiu&pwd=123456",
type: "GET",
//contentType: "application/json;",
success: function(result) {
alert(result.status);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("出错!XMLHttpRequest:" + XMLHttpRequest.status);
}
});

这样访问就ok了。

随机推荐

  1. Sql语句之select 5种查询

    select 5种子句:注意顺序where / group by /having / order by / limit / 清空表中的数据:truncate 表名: 导入表结构(不含数据): crea ...

  2. iOS&lowbar;10&lowbar;tableView的简单使用&lowbar;红楼十二钗

    终于效果图: 方式1,用字典数组 BeyondViewController.h // // BeyondViewController.h // 10_tableView // // Created b ...

  3. js数组操作-打乱数组

    <style> html, body { margin: 0; padding: 0;} div span { display: inline-block; width: 25px; he ...

  4. HTML5的应用缓存

    HTML5:提供一种应用缓存机制,使得基于web的应用程序可以离线运行.开发者可以使用  Application Cache (AppCache)  接口设定浏览器缓存的数据并使得数据离线有效. 在处 ...

  5. 9 ArcGIS Server 性能优化

    1.系统性能影响因子 地图.服务类型.数据源.客户端技术.CPU.数据结构.网络.内存.存储.部署.架构.服务接口.SDE等. 2.ArcGIS Server性能优化 数据结构与数据源:数据结构(矢量 ...

  6. &lbrack;iOS&rsqb;深入理解GCD

    看到一篇很好的文章,本来想翻译的,但发现已经有人翻译了,遂简单整理了一下,方便阅读学习 新博客[wossoneri.com] 什么是GCD GCD(Grand Central Dispatch)是li ...

  7. python 全栈开发,Day102&lpar;支付宝支付&rpar;

    昨日内容回顾 1. django请求生命周期? - 当用户在浏览器中输入url时,浏览器会生成请求头和请求体发给服务端 请求头和请求体中会包含浏览器的动作(action),这个动作通常为get或者po ...

  8. Jmeter(二十七)模拟发送TCP&sol;UDP&sol;HTTP&sol;FTP等请求包(转载)

    转载自 http://www.cnblogs.com/yangxia-test JMeter安装UDP插件后支持发送UDP协议的请求包,官方介绍安装插件后可以用来测试DNS, NTP, TFTP, B ...

  9. &vert;和&vert;&vert;、&amp&semi;&amp&semi;和&amp&semi;

    |和||.&&和& | : 会检查每一个 条件的真伪,再做“或”运算 ||: 按照条件写的顺序,直到一个为true时,后面的条件则不再检查,直接进入条件 & : 会检查 ...

  10. Joint Stacks---hdu5818(栈模拟)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5818  有3个操作pop,push,merge A B; 引入一个新的栈C,每次合并的时候就把A和B合 ...