Web API - Access Custom Attribute Properties inside ActionFilterAttribute OnActionExecuting

801 views Asked by At

I need to access a property inside a custom DataAnnotation attribute. How can I access this attribute in order to set the response value? The attribute is added to the model property.

public class BirthDateAttribute : ValidationAttribute
{
    public string ErrorCode { get; set; }
    ....
}

public class ValidateModelAttribute : ActionFilterAttribute
{                
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (!actionContext.ModelState.IsValid)
        {
            List<Errors> errors = new List<Errors>();

            // Set error message and errorCode
            foreach (var key in keys)
            {
                if (!actionContext.ModelState.IsValidField(key))
                {
                    error.Add(new HttpResponseError
                    {
                        Code = ???????????,
                        Message = actionContext.ModelState[key].Errors.FirstOrDefault().ErrorMessage
                    });
                }
            }                

            // Return to client
            actionContext.Response = actionContext.Request.CreateResponse(
                HttpStatusCode.BadRequest, errors);
       }
    }
}
1

There are 1 answers

2
Vivek N On

Assuming that the custom attribute is applied to the controller, you can try following in the OnActionExecuting event. This similar thing works with MVC controller but should work with API controller too.

 var att = actionContext.ControllerContext.GetType().GetCustomAttributes(typeof(BirthDateAttribute), false)[0] as BirthDateAttribute;
                string errorCode = att.ErrorCode;

As mentioned by OP, if this is on a class (Model), it should be pretty starightforward because the type is already known. Replace the Model class.

var att = <<ModalClass>>.GetCustomAttributes(typeof(BirthDateAttribute), false)[0] as BirthDateAttribute;
                    string errorCode = att.ErrorCode;