2016-03-15 51 views
0

我碰到過這段代碼,因爲它引用了HttpContext,所以無法對它進行測試。我如何刪除對HttpContext的依賴關係以使其成爲可測試的?如何從AuthorizationFilterAttribute中重構出HttpContext進行測試?

public class AuthorizeByUserStatus :AuthorizationFilterAttribute 
{ 
    private readonly UserStatusEnum status; 

    public AuthorizeByUserStatus(UserStatusEnum status) 
    { 
     this.status = status; 
    } 

    public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken) 
    { 
     var authorize = false; 
     var user = HttpContext.Current.User; 
     var userIdentity = user.GetIdentity(); 

     if (userIdentity.UserStatus >= status) 
     { 
      authorize = true; 
     } 

     if (authorize) 
     { 
      base.OnAuthorization(actionContext); 
     } 
     else 
     { 
      throw new HttpResponseException(HttpStatusCode.Unauthorized); 
     } 
    } 
} 

回答

0

替換靜態的HttpContext方法並引用傳入的actionContext中有我們需要的信息!

var userIdentity = actionContext.RequestContext.Principal.GetIdentity(); 

您現在可以通過與正確設置請求細節ActionContext中得到的請求用戶身份。

相關問題