4

I tried the validation example code for web api on the latest mvc 4 download and I'm getting some errors. Does anyone have an updated example of the ValidationActionFilter class.

Here's the original code

public class ValidationActionFilter : ActionFilterAttribute 
{ 
    public override void OnActionExecuting(HttpActionContext context) 
    { 
        var modelState = context.ModelState; 
        if (!modelState.IsValid) 
        { 
            dynamic errors = new JsonObject(); 
            foreach (var key in modelState.Keys) 
            { 
                var state = modelState[key]; 
                if (state.Errors.Any()) 
                { 
                    errors[key] = state.Errors.First().ErrorMessage; 
                } 
            } 

            context.Response = new HttpResponseMessage<JsonValue>(errors, HttpStatusCode.BadRequest); 
        } 
    } 
}

I'm getting an error on HttpResponseMessage

The non-generic type 'System.Net.Http.HttpResponseMessage' cannot be used with type arguments

Also it looks like I need to add a Json reference, but should I be using JSON.net instead? An example of this using Json.net?

j0k
  • 22,600
  • 28
  • 79
  • 90
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460
  • Check more answer in this: http://stackoverflow.com/questions/11686690/handling-modelstate-validation-with-asp-net-web-api/11724405#11724405 – cuongle Oct 14 '12 at 15:44
  • Check this blog post out: http://www.tugberkugurlu.com/archive/asp-net-web-api-and-handling-modelstate-validation – tugberk Oct 14 '12 at 19:59

1 Answers1

2

HttpResponseMessage<T> is from version beta, it no longer exists in the version release, use below instead:

 actionContext.Response = actionContext.Request
                              .CreateResponse(HttpStatusCode.BadRequest, errors);
cuongle
  • 74,024
  • 28
  • 151
  • 206