C# 用于筛选asp.net核心REST方法的中间件
我有一个带有几个REST操作的.net核心应用程序(请参见下面的代码),类似于以下内容:C# 用于筛选asp.net核心REST方法的中间件,c#,rest,asp.net-core,asp.net-core-mvc,.net-core,C#,Rest,Asp.net Core,Asp.net Core Mvc,.net Core,我有一个带有几个REST操作的.net核心应用程序(请参见下面的代码),类似于以下内容: namespace Controllers { [Route("system")] public class SystemController : Controller { // This is a public access method [HttpGet("dictionaries/{name}")]
namespace Controllers
{
[Route("system")]
public class SystemController : Controller
{
// This is a public access method
[HttpGet("dictionaries/{name}")]
public List GetDictionary(HttpRequestMessage requestMsg, string name)
{
// etc
}
// This function shall be accessible only by an admin role
[AdminRole]
[HttpPost("dictionaries/{name}")]
public IActionResult PostDictionary(HttpRequestMessage requestMsg, string name)
{
// etc
}
}
}
命名空间控制器
{
[路线(“系统”)]
公共类SystemController:控制器
{
//这是一种公共访问方法
[HttpGet(“字典/{name}”)]
公共列表GetDictionary(HttpRequestMessageRequestMsg,字符串名称)
{
//等
}
//此功能只能由管理员角色访问
[管理员角色]
[HttpPost(“字典/{name}”)]
公共IActionResult PostDictionary(HttpRequestMessage requestMsg,字符串名称)
{
//等
}
}
}
我想将某些操作标记为只能由某些角色(即管理员)访问。一种优雅的方法是使用属性
现在,我想确定根据URL捕获要调用的C#方法的正确中间件实现,并使用反射获取角色属性(如果有),以便阻止未经授权的调用
请给出建议。我想提请注意,以下方法仅适用于您出于某种原因不想使用内置功能的情况(如问题注释中所述)
如果您创建一个全局(它是MVC的一部分,因此可以使用“控制器逻辑”进行操作),您可以从ActionExecutingContext
获取所有需要的信息:
public class SampleActionFilter : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
//Provides information about an action method, such as its name, controller, parameters, attributes, and filters.
var actionDescriptor = context.ActionDescriptor;
//Gets the controller instance containing the action.
var controller = context.Controller;
// Gets the arguments to pass when invoking the action. Keys are parameter names.
var actionArgs = context.ActionArguments;
}
...
}
context.ActionDescriptor
可以强制转换为。允许直接使用以下属性:
public class ControllerActionDescriptor : ActionDescriptor
{
public string ControllerName { get; set; }
public virtual string ActionName { get; set; }
public MethodInfo MethodInfo { get; set; }
public TypeInfo ControllerTypeInfo { get; set; }
...
}
不确定是否可以使用中间件,因为控制器是MVC中间件的一部分。如果您将中间件放在它之前,那么在管道步骤中还没有“控制器”逻辑。如果在-之后,对于您想要的东西来说已经太晚了。属性不是已经在做您想要的事情了吗,就像在[Authorize(Roles=“Administrator”)]
中一样?检查