在验证上下文中使用 HttpRequest

Ori*_*ael 3 c# validation httpcontext .net-core asp.net-core

在 .net Framework <= 4.7.2 中,在验证上下文中,您可以HttpRequest通过访问HttpContext.

例如,我有一段代码如下所示:

public sealed class AccessValidator : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext context)
    {
        // validate stuff, if all true -> yield ok.

        // if is not valid
        var request = HttpContext.Current.Request;

        // store/log the request payload.
    }

}
Run Code Online (Sandbox Code Playgroud)

使用 .net Core 2.1 时无法做到这一点。我看到了一个关于注入IHttpContextAccessor什么的帖子,但它几乎在每个地方都暴露了请求。

由于这是我服务器的外部库,我希望它不依赖于服务器代码注入,因为那样会产生我不想成为的依赖。

有没有已知的方法来处理这个或解决这个问题?

Kir*_*kin 9

您可以组合实现这一目标IHttpContextAccessorValidationContext.GetService。这是它的样子:

protected override ValidationResult IsValid(object value, ValidationContext context)
{
    // validate stuff, if all true -> yield ok.

    // if is not valid
    var httpContextAccessor = (IHttpContextAccessor)context.GetService(typeof(IHttpContextAccessor));
    var request = httpContextAccessor.HttpContext.Request;

    // store/log the request payload.
}
Run Code Online (Sandbox Code Playgroud)

它没有使用依赖注入,而是使用服务定位器模式(被认为是一种模式,但它可能是你唯一真正的选择)。

您还需要在 中配置IHttpContextAccessorDI 容器Startup.ConfigureServices,如下所示:

services.AddHttpContextAccessor();
Run Code Online (Sandbox Code Playgroud)