Ori Refael
Ori Refael

Reputation: 3028

Use HttpRequest in validation context

in .net Framework <= 4.7.2, in validation context, you could get the current HttpRequest by accessing the HttpContext.

For example, I had a piece of code which looked like this:

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.
    }

}

This cannot be done when using .net Core 2.1. I saw a post regarding injection of IHttpContextAccessor or something, but it exposes the request in almost every place.

Since this is an external library to my server, I wish it not rely on server code injections because then it creates a dependence I don't want to be.

Is there any known way to handle this or around this?

Upvotes: 6

Views: 4116

Answers (1)

Kirk Larkin
Kirk Larkin

Reputation: 93293

You can achieve this with a combination of IHttpContextAccessor and ValidationContext.GetService. Here's what it would look like:

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.
}

Rather than using dependency injection, it uses the Service Locator pattern (considered an anti-pattern, but it might be your only real option here).

You'll also need to configure IHttpContextAccessor with the DI container in Startup.ConfigureServices, like this:

services.AddHttpContextAccessor();

Upvotes: 12

Related Questions