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上标记此特性就可以了

posted on 2013-04-08 17:09  认真的我  阅读(3836)  评论(0编辑  收藏  举报