$.ajax 跨域请求 Web Api
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了。
随机推荐
- 个人理解的javascript作用域链与闭包
闭包引入的前提个人理解是为从外部读取局部变量,正常情况下,这是办不到的.简单的闭包举例如下: function f1(){ n=100; function f2(){ alert(n); } retu ...
- ADV-caikuang
#include<stdio.h> int step[99][99]; int sum; int min=999999; int cas; int N; int H; int V; int ...
- js高级应用
特别板块:js跨域请求Tomcat6.tomcat7 跨域设置(包含html5 的CORS) 需要下载两个jar文件,cors-filter-1.7.jar,Java-property-utils-1 ...
- 第四章 使用Docker镜像和仓库(二)
第四章 使用Docker镜像和仓库(二) 回顾: 开始学习之前,我先pull下来ubuntu和fedora镜像 [#9#cloudsoar@cloudsoar-virtual-machine ~]$s ...
- flex中通过代码获取supermap的token
最近工作中需要使用代码来获取supermap服务启动安全访问限制以后的token值,经过一番尝试,最终成功获取到,记录下里,以供翻阅 //get token public function getTo ...
- iOS遍历相册中的图片
//获取相册的所有图片 - (void)reloadImagesFromLibrary { self.images = [[NSMutableArray alloc] init]; dispatch_ ...
- UITextField使用详解
转iOS中UITextField使用详解 (1) //初始化textfield并设置位置及大小 UITextField *text = [[UITextField alloc]initWithFr ...
- sql server操作类(本人自己写的)
package com.mytest; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Prepa ...
- sicily 1007. To and Fro 2016 11 02
// Problem#: 1007// Submission#: 4893204// The source code is licensed under Creative Commons Attrib ...
- java的三元运算符
1.三元运算符语法:判断表达式?表达式1:表达式2: (1)三元运算符适合于判断2个值到底使用哪一个! public static void mian(String[] args){ int sex= ...