1.学习文章:AJAX 跨域请求 - JSONP获取JSON数据
1.asp.net代码
(1).增加CorsHandler类,
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);
}
}
}
(2).添加配置
protected void Application_Start()
{
GlobalConfiguration.Configuration.MessageHandlers.Add(new CorsHandler());
GlobalConfiguration.Configure(WebApiConfig.Register);
}
(3).控制器例子
[RoutePrefix("ajilisiwei")]
public class ShoppingController : ApiController
{
public ShoppingController()
{
List<Product> products = new List<Product>() {
new Product(){Name="Apple",Price="$20/kg"},
new Product(){Name="Banana",Price="$15/kg"},
new Product(){Name="Melon",Price="$20/kg"}
};
shoppingCart.Name = "MyFruitBaskit";
shoppingCart.ProductList = products;
}
[Route("Test")]
[HttpGet]
public IEnumerable<Product> GetFruitListByNetJson()
{
return shoppingCart.ProductList;
}
}
(4).js 代码
$.ajax({
url: "http://localhost:1867/ajilisiwei/Test",
type: "GET",
contentType: "application/json;",
success: function(result) {
console.log(result);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("出错!XMLHttpRequest:" + XMLHttpRequest.status);
}
});
方法二.jsop
(1).Action代码
[Route("TestJsonp")]
[HttpGet]
public string GetFruitListByJsonp()
{
return new JavaScriptSerializer().Serialize(shoppingCart.ProductList);
}
(2).js代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="./js/jquery.min.js"></script>
</head>
<body>
<script>
$.getJSON("http://localhost:1867/ajilisiwei/TestJsonp?jsonpcallback=test", //"test" 这里除了写问号,随便写啥都可以,好奇怪
function(json) {
console.log(json);
}
);
</script>
</body>
</html>
说明: 还有这种方法。
$.ajax({
type: "get",
url: "http://localhost:1867/ajilisiwei/TestJsonp",
//dataType: "jsonp",
jsonp: "jsonpcallback",
data: "jsonpcallback=?",
success: function (json) {
console.log(json);
}
});
type: "get",
url: "http://localhost:1867/ajilisiwei/TestJsonp",
//dataType: "jsonp",
jsonp: "jsonpcallback",
data: "jsonpcallback=?",
success: function (json) {
console.log(json);
}
});
验证了好久, 不用增加 dataType:"jsonp" 设置。url内容如下:http://localhost:1867/ajilisiwei/TestJsonp?jsonpcallback=? 这是在asp.net web api下验证的