您的位置:首页 > 其它

WebApi 自定义过滤器实现支持AJAX跨域的请求

2015-09-10 15:32 531 查看
我想关于此类话题的文章,大家一搜铺天盖地都是,我写此文的目的,只是对自己学习过程的记录,能对需要的朋友有所帮助,也百感荣幸!!!废话不多说,直接上代码!

客户端:很简单的AJAX请求

<html>
<head>
<title id='Description'>WebApi支持Ajax跨域</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {

$.ajax({
type: "POST",
url: "https://192.168.1.9/api/values/get",

success: function (persons) {

alert('persons');

},
error: function () {
alert('fail');
}
});

});
</script>
</head>
<body class='default'>
</body>
</html>


WebApi服务端:

1.自定义EnableCorsAttribute类,继承于System.Web.Http.Filters.ActionFilterAttribute ,重写OnActionExecuted方法如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.Filters;

namespace ResourceServer
{
public class EnableCorsAttribute : System.Web.Http.Filters.ActionFilterAttribute
{

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Origin"))
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Headers"))
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type,Accept");
}
if (!actionExecutedContext.Response.Headers.Contains("Access-Control-Allow-Methods"))
{
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Methods", "GET,POST");
}
}
}
}


2.上一部完成后,也已经大功告成,此步直接在想支持跨域Controller的Action的方法上添加标记,就能实现AJAX的跨域调用了。:)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.OData;
using Newtonsoft.Json;
using WebApiThrottle;

namespace ResourceServer.Controllers
{
public class People {
public string Name { get; set; }
public int Age { get; set; }

}

public class ValuesController : ApiController
{

public static List<People> li = new List<People>{

new People{ Name="李刚", Age=19},
new People{ Name="王六", Age=20}

};
// GET api/<controller>
[EnableCors]//此特性添加就支持跨域访问了
[HttpPost]
[HttpGet]
[EnableQuery()]
[EnableThrottling(PerMinute=5)]
public List<People> Get()
{
return li;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: