2

I using asp.net core API and My question is

How will I access request context in custom attribute, Actually I am sending TimeZone info in request Header that I want to access here.

My C# Date validation Code is

public class DateRangeAttribute : ValidationAttribute
{
    public string StartDate { get; set; }
    public string EndDate { get; set; }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (validationContext == null)
        {
            throw new ArgumentNullException();
        }
       return new ValidationResult("Date is not in given range.", new List<string>() {
                                                validationContext.MemberName 
                                  });
        }
    }

My Model is

[DateRange(StartDate = "01/01/2000", EndDate = "12/31/9999")]
public DateTime StartWork { get; set; }
1
  • 1
    Please note that If you are accessing the validationContext and it's required by the attribute, you should override the RequiresValidationContext and set it to true. This is better than raise argument null exception if the validation context is null. learn.microsoft.com/en-us/dotnet/api/… Commented May 3, 2023 at 8:18

2 Answers 2

3

You can use ValidationContext.GetService to get IHttpContextAccessor. It will allow you to get the current HttpContext.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank You. Actually I was passing IHttpContextAccessor that was the problem
I forgot to pass IHttpContextAccessor
2

You can create a static class

public static class HttpHelper
{
     private static IHttpContextAccessor _accessor;
     public static void Configure(IHttpContextAccessor httpContextAccessor)
     {
          _accessor = httpContextAccessor;
     }

     public static HttpContext HttpContext => _accessor.HttpContext;
}

Then assigning the IHttpContextAccessor in the Startup Configure should do the job.

HttpHelper.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());

I guess you should also need to register the service singleton:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

now you can get your HttpContext everywhere:

HttpHelper.HttpContext 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.