2016-10-18 10 views

答えて

1

私はカスタム属性が行く方法だと思います。ここで

は私のコードです:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 
using System.Web.Http.Controllers; 

namespace YourFancyNamespace 
{ 
    public class AuthorizeExtended : AuthorizeAttribute 
    { 
     private string _notInRoles; 
     private List<string> _notInRolesList; 

     public string NotInRoles 
     { 
      get 
      { 
       return _notInRoles ?? string.Empty; 
      } 
      set 
      { 
       _notInRoles = value; 
       if (!string.IsNullOrWhiteSpace(_notInRoles)) 
       { 
        _notInRolesList = _notInRoles 
         .Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries) 
         .Select(r => r.Trim()).ToList(); 
       } 
      } 
     } 

     public override void OnAuthorization(HttpActionContext actionContext) 
     { 
      base.OnAuthorization(actionContext); 
      if (_notInRolesList != null && _notInRolesList.Count > 0) 
      { 
       foreach (var role in _notInRolesList) 
       { 
        if (actionContext.RequestContext.Principal.IsInRole(role)) 
        { 
         actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); 
        } 
       } 
      } 
     } 
    } 
} 

そして、ここでは、あなたがそれを使用する方法である。

// A AuthorizeExtendedは(ロールフィルタ付き)承認に等しい+すべての厄介なユーザー

[AuthorizeExtended(Roles = "User", NotInRoles="PeskyUser")] 
[HttpPost] 
[Route("api/Important/DoNotForgetToUpvote")] 
public async Task<IHttpActionResult> DoNotForgetToUpvote() 
{ 
    return Ok("I did it!"); 
} 
を除外します

//БAuthorizeExtendedは平等と等しいすべての厄介なユーザーを承認+除外

[AuthorizeExtended(NotInRoles="PeskyUser")] 
[HttpPost] 
[Route("api/Important/DoNotForgetToUpvote")] 
public async Task<IHttpActionResult> DoNotForgetToUpvote() 
{ 
    return Ok("I did it!"); 
} 

//ВAuthorizeExtendedは承認

[AuthorizeExtended] 
[HttpPost] 
[Route("api/Important/DoNotForgetToUpvote")] 
public async Task<IHttpActionResult> DoNotForgetToUpvote() 
{ 
    return Ok("I did it!"); 
} 
に等しい
関連する問題