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?

2

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

5 Comments

also do you know how this code would be updated for Json.net since it looks like they removed System.Json
@MonkeyBonkey: for the release version, System.Json is no longer used, Newtonsoft.Json is used instead
for errors, what would I use instead of new JsonObject()? Would it just be new Dictionary<string, string>() and the json serializer will automatically serialize the response somewhere else in the flow?
@MonkeyBonkey: Ah I got it, you can use JObject
@MonkeyBonkey: remember adding using Newtonsoft.Json.Linq

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.