2014-07-10 71 views
5

我在Windows身份驗證背後使用ASP.Net Web API,並使用[Authorize]屬性來規定用戶有權訪問哪些控制器和功能。這很好。問題是我希望幫助區域只反映用戶被授予訪問權限。好奇是否有人以某種方式實現了這一點。這是在控制器,App Start或幫助控制器的級別完成的。ASP.Net基於授權的Web Api幫助頁面

在此先感謝...

我控制器

[Authorize] 
public class TaktTimeController : ApiController 
{ 
    private BIDataContainer db = new BIDataContainer(); 

    // GET api/TaktTime 
    [Authorize(Roles="Admins")] 
    public IQueryable<TaktTime> GetTaktTimes() 
    { 
     return db.TaktTimes; 
    } 

    // GET api/TaktTime/5 
    [ResponseType(typeof(TaktTime))] 
    [Authorize(Roles = "Admins")] 
    public IHttpActionResult GetTaktTime(string id) 
    { 
     TaktTime takttime = db.TaktTimes.Find(id); 
     if (takttime == null) 
     { 
      return NotFound(); 
     } 

     return Ok(takttime); 
    } 

回答

1

這可以在Razor視圖類似以下操作來實現將是你所需要的之一的代碼段。

@if (User.IsInRole("admin")) 
{ 
    <div> 
     <!--Text for admin here--> 
    </div> 
} 
@if (User.IsInRole("user")) 
{ 
    <div> 
     <!--Text for user here--> 
    </div> 
} 

同樣的邏輯可以的WebAPI控制器一起使用

public string Get() 
{ 
    if(User.IsInRole("admin")) 
    { 
     return "Text for admin"; 
    } 

    if(User.IsInRole("user")) 
    { 
     return "Text for user"; 
    } 
} 
1

您將需要修改HelpController.cs並添加下面的方法:

using System.Collections.ObjectModel; 

private Collection<ApiDescription> FilteredDescriptions() 
{ 
    var desctiptionsToShow = new Collection<ApiDescription>(); 

    foreach (var apiDescription in Configuration.Services.GetApiExplorer().ApiDescriptions) 
    { 
     var actionDescriptor = apiDescription.ActionDescriptor as ReflectedHttpActionDescriptor; 
     var authAttribute = actionDescriptor?.MethodInfo.CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == nameof(System.Web.Http.AuthorizeAttribute)); 
     var roleArgument = authAttribute?.NamedArguments?.FirstOrDefault(x => x.MemberName == nameof(System.Web.Http.AuthorizeAttribute.Roles)); 
     var roles = roleArgument?.TypedValue.Value as string; 
     if (roles?.Split(',').Any(role => User.IsInRole(role.Trim())) ?? false) 
     { 
      desctiptionsToShow.Add(apiDescription); 
     } 
    } 
    return desctiptionsToShow; 
} 

而從指數叫它()動作:

return View(FilteredDescriptions());