4
votes

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?

1
Check more answer in this: stackoverflow.com/questions/11686690/…cuongle
Check this blog post out: tugberkugurlu.com/archive/…tugberk

1 Answers

2
votes

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);