首页 > 代码库 > WebAPI 过滤器拦截处理以及异常捕获
WebAPI 过滤器拦截处理以及异常捕获
对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 =http://www.mamicode.com/= 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); } }); }
WebAPI 过滤器拦截处理以及异常捕获
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。