动静分离跨域自定义请求头部信息

环境: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);
                }
            })
        })

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值