webapi權限控制


webapi中的權限控制與mvc中的權限控制大致雷同,只是ActionFilterAttribute的命名空間不同

在mvc中,如當前用戶沒有權限,直接在自己的 ActionFilterAttribute 中return就可以,但是在webapi中需要執行  actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);才可以

我項目中的代碼如下

AuthenticationApiAttribute
 1 using System;
 2 using System.Net;
 3 using System.Net.Http;
 4 using System.Web;
 5 using System.Web.Http.Controllers;
 6 using System.Web.Http.Filters;
 7 using FrameWork.Core.Extends;
 8 using iAssistantAPI.Authentication;
 9 using iAssistantAPI.Models;
10 
11 namespace iAssistantAPI.APIAttributes
12 {
13     /// <summary>
14     /// 基本驗證Attribtue,用以Action的權限處理
15     /// </summary>
16     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
17     public class AuthenticationApiAttribute : ActionFilterAttribute
18     {
19         /// <summary>  
20         /// 檢查用戶是否有該Action執行的操作權限  
21         /// </summary>  
22         /// <param name="actionContext"></param>  
23         public override void OnActionExecuting(HttpActionContext actionContext)
24         {
25             if (LocalSetting.GetLocalSetting().EnablePermission)
26             {
27                 if ((HttpContext.Current.Request.QueryString["HCPTicket"]).IsNullOrEmptyOrBlank())
28                 {
29                     HttpContext.Current.Response.Redirect("~/api/DenyAnonymousAccess/DenyAnonymous");
30                     actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
31                     return;
32                 }
33                 else
34                 {
35                     string ticket = HttpContext.Current.Request.QueryString["HCPTicket"].ToString();
36                     ReturnModel rm = IdentityTicket.CheckTicketIsNotTimeOut(ticket);
37                     if (rm.Result == false)
38                     {
39                         ////HttpContext.Current.Response.Write("{\"Result\":false,\"Info\":\"" + rm.Info + "\",\"RowCount\":0,\"ReturnData\":null}");
40                         HttpContext.Current.Response.Redirect("~/api/DenyAnonymousAccess/LoginTimeout");
41                         actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized);
42                         return;
43                     }
44                 }
45             }
46             else
47             {
48                 base.OnActionExecuting(actionContext);
49             }
50         }
51 
52         /// <summary>
53         /// 執行Action之后
54         /// </summary>
55         /// <param name="actionExecutedContext"></param>
56         public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
57         {
58             base.OnActionExecuted(actionExecutedContext);
59         }
60     }
61 }


在需要權限控制的 action上或者control上標記此特性就可以了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM