I am using json.net(newtonsoft) and I want to build a json request but I have 2 different dictionaries and not sure how to join them.
Dictionary<string, HttpStatusCode> code = new Dictionary<string, HttpStatusCode>();
code.Add("Message", statusCode);
Dictionary<string, IErrorInfo> modelState = new Dictionary<string, IErrorInfo>();
// some code to add to this modelState
Edit
IErrorInfo just has some properties
public interface IErrorInfo
{
SeverityType SeverityType { get; set; }
ValidationType ValidationType { get; set; }
string Msg { get; set; }
}
The result I trying to go for is something like this
{
"Message": 400, // want this to be text but not sure how to do that yet (see below)
"DbError":{
"SeverityType":3,
"ValidationType":2,
"Msg":"A database error has occurred please try again."
}
}
I am basically trying to achieve this.
HttpError and Model Validation
For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response:
public HttpResponseMessage PostProduct(Product item)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
// Implementation not shown...
}
This example might return the following response:
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
Content-Length: 320
{
"Message": "The request is invalid.",
"ModelState": {
"item": [
"Required property 'Name' not found in JSON. Path '', line 1, position 14."
],
"item.Name": [
"The Name field is required."
],
"item.Price": [
"The field Price must be between 0 and 999."
]
}
}
The reason why I am not using this built in method is because I have a separate built in class library that has all my business logic in it. I want to keep it so that it has no dependency on web stuff or mvc stuff(like modelState).
This is why I created my own sort of model state with a bit of extra stuff in it.
You should be able to just use one Dictionary and add items from both of your dictionaries into this dictionary. Json.NET should serialize it all like you’re expecting.