gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:22:41 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com