c# - 基于授权的 ASP.Net Web Api 帮助页面

标签 c# asp.net asp.net-web-api

我在 Windows 身份验证背后使用 ASP.Net Web API,并使用 [Authorize] 属性来指示用户可以访问哪些 Controller 和功能。这很好用。问题是我想让帮助区域只反射(reflect)用户被授予访问权限的内容。好奇是否有人以某种方式实现了这一目标。这是在 Controller 、App Start 或帮助 Controller 级别完成的。

提前致谢...

我的一个 Controller 的代码片段

[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);
    }

最佳答案

您需要修改 HelpController.cs 并添加以下方法:

using System.Collections.ObjectModel;

private Collection<ApiDescription> FilteredDescriptions()
{
    var descriptionsToShow = 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)
        {
            descriptionsToShow.Add(apiDescription);
        }
    }
    return descriptionsToShow;
}

并从 Index() 操作中调用它:

return View(FilteredDescriptions());

关于c# - 基于授权的 ASP.Net Web Api 帮助页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24685395/

相关文章:

c# - 通过 Controller .Net Core 中的 ActionExecutingContext 获取自定义属性

c# - 有开源的 asp.net 服务器吗?

asp.net - ASP ReportViewer 显示大显示/隐藏参数栏

没有带数据库事务或 TransactionScope 的 EF 的 C# UnitOWork 实现

c# - c#中的JavaScript拼接

c# - 在 WPF 中使用 CollectionView 时无法从数据集中的连接表中获取数据

c# - ObservableCollection 中的 SelectedItem

ASP.NET Core 身份 - UserManager 和 UserStore 问题

asp.net-mvc - asp.net mvc/webapi 5 的( headless )集成测试框架

c# - 找不到类型或命名空间(但应该是!)