Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 789
Ori Refael Avatar asked Jan 01 '23 16:01

Ori Refael


1 Answers

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();
like image 101
Kirk Larkin Avatar answered Jan 09 '23 15:01

Kirk Larkin