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":{"c omment.Aut hor":["Aut hor 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(Htt pStatusCod e.BadReque st, "{\"Message\":\"The request is invalid.\",\"ModelState\": {\"comment .Author\": [\"Author is too long! This was validated on the server.\"]}}");
throw new HttpResponseException(resp onse);
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?
If I could pass this..
{"Message":"The request is invalid.","ModelState":{"c
in the message response I would achieve my goal.
This is the correct string...
var response = Request.CreateResponse(Htt
throw new HttpResponseException(resp
but the payload then comes back as a string rather than a JSON object...
like this...
"{\"Message\":\"The request is invalid.\",\"ModelState\":
So... how can I return it as a JSON object where I custom build it?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Perfect! Just what I needed!
ASKER
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>
throw new HttpResponseException(resp