public class AuthFilter : Attribute, IActionFilter { public void OnActionExecuted(ActionExecutedContext context) { } private JsonResult ErrJsonResult(string str) { return new JsonResult(JsonHelper.ToJson(OperateResult.Error(str))); //context.Result = new ContentResult() //{ // Content = str, // ContentType = "JSON", // StatusCode=0 //}; } /// <summary> /// 32位MD5加密 /// </summary> /// <param name="input"></param> /// <returns></returns> private string Md5Hash(string input) { System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } public void OnActionExecuting(ActionExecutingContext context) { context.HttpContext.Response.Headers.Add("My-Header", "WebApiFrame-Header"); //JsonResult json = new JsonResult(JsonHelper.ToJson(OperateResult.Succeed("获取成功"))); //context.Result = json; //ErrorRedirect(context); var request = context.HttpContext.Request; var method = request.Method; var staffId = "^和JS端需要对应$"; string timestamp = string.Empty, nonce = string.Empty, signature = string.Empty; if (request.Headers.ContainsKey("timestamp")) timestamp = request.Headers["timestamp"].FirstOrDefault(); if (request.Headers.ContainsKey("nonce")) nonce = request.Headers["nonce"].FirstOrDefault(); if (request.Headers.ContainsKey("signature")) signature = request.Headers["signature"].FirstOrDefault(); if (string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(signature)) { context.Result = ErrJsonResult( "参数错误"); return; } double ts = 0; bool timespanvalidate = double.TryParse(timestamp, out ts); //double c = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds - ts; bool falg = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds - ts > 60 * 1000; if (falg || (!timespanvalidate)) { context.Result = ErrJsonResult("timeSpanValidate"); return; } var data = string.Empty; IDictionary<string, string> sortedParams = null; switch (method.ToUpper()) { case "POST": case "PUT": case "DELETE": //InputStream Stream stream = context.HttpContext.Request.Body; StreamReader streamReader = new StreamReader(stream); sortedParams = new SortedDictionary<string, string>(new JsonSerializer().Deserialize<Dictionary<string, string>>(new JsonTextReader(streamReader))); break; case "GET": IDictionary<string, string> parameters = new Dictionary<string, string>(); foreach (string key in context.HttpContext.Request.Query.Keys) { if (!string.IsNullOrEmpty(key)) { parameters.Add(key, context.HttpContext.Request.Query[key]); } } sortedParams = new SortedDictionary<string, string>(parameters); break; default: context.Result = ErrJsonResult("defaultOptions"); return; } StringBuilder query = new StringBuilder(); if (sortedParams != null) { foreach (var sort in sortedParams.OrderBy(k => k.Key)) { if (!string.IsNullOrEmpty(sort.Key)) { query.Append(sort.Key).Append(sort.Value); } } data = query.ToString().Replace(" ", ""); } var md5Staff = Md5Hash(string.Concat(timestamp + nonce + staffId + data)); if (!md5Staff.Equals(signature)) { context.Result = ErrJsonResult("md5Staff"); return; } } // 错误处理方法 private void ErrorRedirect(ActionExecutingContext filterContext) { filterContext.Result = new RedirectToRouteResult("Default", new RouteValueDictionary(new { controller = "Home", action = "Default" })); } // end ErrorRedirect //当执行ErrorRedirect方法时,它会自己选择指定的Route并跳转到非AdminIndex的Action中. //public override void OnActionExecuting(HttpActionContext actionContext) //{ // // // 所有维护用api请求都要求验证登录 // // if (!IsLogined()) // // { // // var username = HttpContext.Current.Request.QueryString["name"]; // // var password = HttpContext.Current.Request.QueryString["pwd"]; // // //if (actionContext.ActionArguments != null) // // //{ // // // actionContext.ActionArguments.TryGetValue("user", out username); // // // actionContext.ActionArguments.TryGetValue("pwd", out password); // // //} // // if (!DoLogin(username, password)) // // { // // actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, ApiResult.CreateError("未登录")); // // return; // // } // // } // // base.OnActionExecuting(actionContext); //} //private bool DoLogin(string userName = "", string md5Pwd = "") //{ // // 登录验证 //} //private bool IsLogined() //{ // // 通过cookie或Session判断是否登录 //} }
使用方法
如 UserController 控制器,[AuthFilte]加上标签就会对函数验证
[Route("api/[controller]/[action]")] public class UserController : Controller { // GET: api/<controller>/<action> [HttpGet] [AuthFilter] public string HasBindUser(string openid) { if(string.IsNullOrEmpty(openid)) { return JsonHelper.ToJson(OperateResult.Error("缺少openid参数")); } string sql = "SELECT EmpID FROM dbo.WXMiniUserBind WHERE OpenID=@OpenID AND EmpID IS NOT null"; int empid = Convert.ToInt32(SqlHelper.ExecuteScalar(sql, new string[,] { { "@OpenID", openid } })); if(empid!=0) { return JsonHelper.ToJson(OperateResult.SucceedData(empid)); } return JsonHelper.ToJson(OperateResult.Error("请绑定用户")); } [HttpGet] public string Test() { return "I'm Test"; } }