c# – 如何从authrizationhandler .net核心获取params

前端之家收集整理的这篇文章主要介绍了c# – 如何从authrizationhandler .net核心获取params前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用授权处理程序将自定义授权放在.net核心的控制器中.如何从控制器获取参数并将其用于授权处理程序.

在旧的.net中,我可以像这样从Httpcontext请求参数中获取参数

var eventId = filterContext.RequestContext.HttpContext.Request.Params["id"];

我不知道如何在.net核心中实现它

enter code here

public class HasAdminRoleFromAnySiteRequirement : AuthorizationHandler<HasAdminRoleFromAnySiteRequirement>,IAuthorizationRequirement
{

    public HasAdminRoleFromAnySiteRequirement()
    {

    }
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,HasAdminRoleFromAnySiteRequirement requirement)
    {   

    //need to call get param from controller to used in the validation
    // something like this 
    //var eventId = filterContext.RequestContext.HttpContext.Request.Params["id"];
   // I tried the suggestion below but I can't get the parameter from routedata
   // var mvcContext = context.Resource as     Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;            

        return Task.FromResult(0);
    }
}

解决方法

在处理程序中,您可以执行以下操作
var mvcContext = context.Resource as 
    Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext;

if (mvcContext != null)
{
    // Examine MVC specific things like routing data.
}

如果需要参数值,则在绑定发生之前运行授权属性块.相反,你会转移到控制器内的强制调用.这基本上是resource based authorization,你的参数是一个资源.

您可以将授权服务注入您的控制器;

public class DocumentController : Controller
{
    IAuthorizationService _authorizationService;

    public DocumentController(IAuthorizationService authorizationService)
    {
        _authorizationService = authorizationService;
    }
}

然后稍微改写你的处理程序;

public class DocumentAuthorizationHandler : AuthorizationHandler<MyRequirement,Document>
{
    public override Task HandleRequirementAsync(AuthorizationHandlerContext context,MyRequirement requirement,Document resource)
    {
        // Validate the requirement against the resource and identity.

        return Task.CompletedTask;
    }
}

您可以看到此处理程序获取文档,这可以是您喜欢的任何内容,无论是ID的整数,还是某种类型的视图模型.

然后,您可以在HandleRequirementAsync()方法中访问它.

最后,一旦绑定发生,你就可以从你的控制器中调用它;

if (await authorizationService.AuthorizeAsync(
    User,document,yourRequirement))
{
}
原文链接:https://www.f2er.com/csharp/243395.html

猜你在找的C#相关文章