1

I am developing an Asp.NET MVC5 project. In my project, I am creating a custom validation attribute. But I am having problem with retrieving posted form data from custom attribute. I am not retrieving property value of ViewModel. I need to retrieve only formcollection value or rote data value in action.

I have action like this

public ActionResult postData(ViewModel model, string routeDta)
{
   //do action here
}

This is my custom attribute needs to retrieve route data

public class RemoteClientServerAttribute : RemoteAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            //I want to retrieve routeDta from action above here
            //It is also ok if I can retrieve form collection value
        }

        public RemoteClientServerAttribute(string routeName)
            : base(routeName)
        {
        }

        public RemoteClientServerAttribute(string action, string controller)
            : base(action, controller)
        {
        }

        public RemoteClientServerAttribute(string action, string controller,
            string areaName)
            : base(action, controller, areaName)
        {
        }
    }

I commented where I want to retrieve data. How can I retrieve form collection value or route data from custom attribute? I am not trying to retrieve property value from ViewModel.

halfer
  • 19,824
  • 17
  • 99
  • 186
Wai Yan Hein
  • 13,651
  • 35
  • 180
  • 372
  • A validation attribute has no knowledge of the HttpContext. You could use `var context = HttpContext.Current;` inside the `IsValid()` method to get the context and access its properties, but what are you trying to do with this code (it makes no sense)? –  Jun 27 '16 at 01:41
  • I need to do it. Please see this question, http://stackoverflow.com/questions/37960095/how-to-create-an-custom-remote-validation-attribute-with-dynamic-additiional-fie . That is the question I asked. I havnt got any solution yet. – Wai Yan Hein Jun 27 '16 at 04:35
  • See comment on previous question. But its not clear why you think you need to do this. Your just degrading your app. –  Jun 27 '16 at 05:41

1 Answers1

0

this below is the way to access HttpContext from the validationContext:

var httpContextAccessor = (IHttpContextAccessor)validationContext.GetService(typeof(IHttpContextAccessor));
        var user = httpContextAccessor.HttpContext.User;
gemon01
  • 181
  • 7
  • Code only answers can almost always be improved by adding some explanation. It also helps to format code as such using the tools in the editor for that, or by indenting with four spaces, or preceding with three back ticks on a line and following with three back ticks on a line. – Jason Aller Mar 04 '20 at 15:53