环境:Asp.net mvc 4 wepapi ,JQuery 1.9.1
1.webapi中Web.config配置项
自定义header项:customHeaderName
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET" />
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type,customHeaderName" />
<add name="Access-Control-Allow-Origin" value="*" /> --可使用固定的域名
</customHeaders>
2.WEBAPI端过滤器代码并在WebApiConfig中注册config.Filters.Add(new ValidationCustomHeaderFilter());
public class ValidationCustomHeaderFilter : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.ActionDescriptor.ActionName == "Login" || actionContext.ActionDescriptor.ActionName == "Logout")
{
base.OnActionExecuting(actionContext);
return;
}
var request = actionContext.Request;
if (request.Method == HttpMethod.Options)
{
base.OnActionExecuting(actionContext);
return;
}
string customHeaderName = string.Empty;
if (request.Headers.Contains("CustomHeaderName"))
{
customHeaderName = HttpUtility.UrlDecode(request.Headers.GetValues("customHeaderName").FirstOrDefault());
}
if (string.IsNullOrEmpty(customHeaderName))
{
actionContext.Response = new HttpResponseMessage { Content = new StringContent("自定义Header不能为空") };
return;
}
try
{
bool validateFlag = ValidationData(customHeaderName);
if (validateFlag)
{
actionContext.Response = new HttpResponseMessage { Content = new StringContent("验证失败") };
return;
}
}
catch (Exception ex)
{
actionContext.Response = new HttpResponseMessage { Content = new StringContent("验证异常:"+ex.Message) };
return;
}
base.OnActionExecuting(actionContext);
}
private bool ValidationData(string customHeaderName)
{
throw new NotImplementedException();
}
}
3.Action需要添加[HttpOptions]
也可以在Global中加上事件
protected void Application_BeginRequest(object sender, EventArgs e)
{
var curContext = HttpContext.Current;
if (curContext.Request.HttpMethod == "OPTIONS")
{
curContext.Response.End();
}
}
4.客户端代码
$(function () {
//全局设置,
//注意:中文需要使用encodeURI否则不生效
$.ajaxSetup({
//方案一
//headers: { "CustomHeaderName": encodeURI(CustomHeaderName)}
//方案二
beforeSend: function (xhr, settings) {
xhr.setRequestHeader("CustomHeaderName", encodeURI(customHeaderValue));
}
})
$.ajax({
type: "get",
url: 'http://localhost:21774/Values/Get?Id=888',
dataType: 'json',
//单个方法中
//方案一
//headers: { "CustomHeaderName": encodeURI(CustomHeaderName)},
//方案二
//beforeSend: function (xhr, settings) {
// xhr.setRequestHeader("CustomHeaderName", encodeURI(customHeaderValue));
//},
success: function (data) {
if (data.IsSuccess) {
alert("data success");
} else {
alert("data error");
}
},
error: function (err) {
alert(err.statusText);
}
})
})