Link to home
Start Free TrialLog in
Avatar of gswitz
gswitz

asked on

Custom response from Web API

My goal is to decide in code when to return a status code of 400 and pass the data necessary to populate validation issues on the web client.

If I could pass this..
{"Message":"The request is invalid.","ModelState":{"comment.Author":["Author is too long! This was validated on the server."]}}

in the message response I would achieve my goal.

This is the correct string...

var response = Request.CreateResponse(HttpStatusCode.BadRequest, "{\"Message\":\"The request is invalid.\",\"ModelState\":{\"comment.Author\":[\"Author is too long! This was validated on the server.\"]}}");
throw new HttpResponseException(response);

but the payload then comes back as a string rather than a JSON object...
like this...
"{\"Message\":\"The request is invalid.\",\"ModelState\":{\"comment.Author\":[\"Author is too long! This was validated on the server.\"]}}"

So... how can I return it as a JSON object where I custom build it?
Avatar of gswitz
gswitz

ASKER

It looks like I can fake it this way, but this isn't exactly what I wanted...

    public class xx
    {
        public Dictionary<string, string> ModelState;
        public string Message { get; set; }
    }


            var xy = new xx();
            xy.Message = "hello world";
            xy.ModelState = new Dictionary<string, string>() { { "comment.Author", "Author is too Long!!" }, { "a", "b" } };
            var response = Request.CreateResponse<xx>(HttpStatusCode.BadRequest, xy );
            throw new HttpResponseException(response);
ASKER CERTIFIED SOLUTION
Avatar of dj_alik
dj_alik

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gswitz

ASKER

Perfect! Just what I needed!