WebAPI 过滤器拦截处理以及异常捕获
时间:2016-09-26 17:54:32
收藏:0
阅读:3470
对action进行拦截处理
public class UserAuthorizeAttribute : ActionFilterAttribute { /// <summary> /// CC调用的Token /// </summary> //private static readonly string CCToken = ConfigurationManager.AppSettings["CCToken"].ToString(); /// <summary> /// WebApi请求监听 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext oHttpActionContext) { string actionName = oHttpActionContext.ControllerContext.RouteData.Values["action"].ToString(); if (actionName == "Login" || actionName == "PostSendSMS") { return; } HttpContextBase oHttpContextBase = (HttpContextBase)oHttpActionContext.Request.Properties["MS_HttpContext"]; //获取传统context string sToken = oHttpContextBase.Request.Form["Token"]; //先从post里面查 if (string.IsNullOrEmpty(sToken)) sToken = oHttpContextBase.Request.QueryString["Token"]; //再从get里面查 //1.验证Token if (string.IsNullOrEmpty(sToken)) { HttpResponseMessage oHttpResponseMessage = new HttpResponseMessage(); oHttpResponseMessage.Content = new StringContent("{‘Flag‘:false,‘Message‘:‘Token为空‘,‘ResultObj‘:null,‘Code‘:‘9101‘}", Encoding.UTF8, "application/json"); throw new HttpResponseException(oHttpResponseMessage); } string CCToken = ConfigurationManager.AppSettings["CCToken"].ToString(); if (sToken == CCToken) { return; } LoginInfoBiz loginBiz = new LoginInfoBiz(); E_LoginInfo value = loginBiz.GetToken(sToken); if (value == null) { HttpResponseMessage oHttpResponseMessage = new HttpResponseMessage(); oHttpResponseMessage.Content = new StringContent("{‘Flag‘:false,‘Message‘:‘Token失效‘,‘ResultObj‘:null,‘Code‘:‘9101‘}", Encoding.UTF8, "application/json"); throw new HttpResponseException(oHttpResponseMessage); } oHttpActionContext.ControllerContext.Request.Properties.Add("ITCode", value.EngCode); } }
ajax调用的时候在error中进行异常捕获,就会获取拦截器里抛出的异常信息
function ApiTest() { $("#result").html(""); $.ajax({ type: $("#type").val(), dataType: "json", url: $("#url").val(), data: eval("(" + $("#data").val() + ")"), success: function (results) { if (typeof results == "object") { $("#result").html(JSON.stringify(results)); } else { var resultObj = JSON.parse(results); $("#result").html(results); } //使用时,需要转换为Json对象 }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.responseText); } }); }
评论(0)