1. 程式人生 > >ApiController實現自定義身份認證

ApiController實現自定義身份認證

del api color span () log list() etc serialize

 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 }

ApiController實現自定義身份認證