ApiController实现自定义身份认证

 1 /// <summary>
 2     /// 身份认证
 3     /// </summary>
 4     public class AuthAttribute : AuthorizationFilterAttribute
 5     {
 6         /// <summary>
 7         /// 重写认证过程
 8         /// </summary>
 9         /// <param name="actionContext"></param>
10         public override void OnAuthorization(HttpActionContext actionContext)
11         {
12             HttpResponseMessage message = new HttpResponseMessage();
13             message.StatusCode = System.Net.HttpStatusCode.OK;
14 
15             var TokenQuery = actionContext.Request.GetQueryNameValuePairs().ToList().Where(m => m.Key == "api_key").FirstOrDefault();
16             if (string.IsNullOrEmpty(TokenQuery.Value))
17             {
18                 string json = JsonConvert.SerializeObject(new ReturnModel() { RetCode = 200, Data = { }, Msg = "token认证失败" });
19                 StringContent Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json");
20                 message.Content = Content;
21 
22                 actionContext.Response = message;
23                 return;
24             }
25             //数据库查询方法
26             //...
27         }
28     }

 

posted @ 2017-11-01 15:59  太阳底下淋雨  阅读(680)  评论(0编辑  收藏  举报