我正在使用json.net(newtonsoft),我想建立一个json请求,但我有2个不同的字典,不知道如何加入它们。
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
编辑
IErrorInfo只有一些属性
public interface IErrorInfo
{
SeverityType SeverityType { get; set; }
ValidationType ValidationType { get; set; }
string Msg { get; set; }
}
我想要的结果是这样的
{
"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."
}
}
我正在努力实现这个目标。
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."
]
}
}
我不使用这个内置方法的原因是因为我有一个单独的内置类库,其中包含我所有的业务逻辑。我想保持它,使它没有依赖于web的东西或mvc的东西(如modelState)。
这就是为什么我创建了自己的模型状态,并在其中添加了一些额外的东西。
您应该能够只使用一个Dictionary并将两个Dictionary中的项添加到这个Dictionary中。Json。. NET应该像你期望的那样序列化它。