我想从我的API返回一个422响应,其中包括了我可以使用的尽可能多的数据模型。我在BaseRepository中创建了一个方法,在其中传递数据和可选消息,以422返回。
protected IHttpActionResult Create422Response<TData>(
TData data,
string message = "Resource validation failed."
)
{
var response = new ResponseObject<TData>(data)
{
Status = "Failure",
Message = message
};
return Content((HttpStatusCode)422, response);
}
在客户端,我正在捕获这样的响应:
var response = await _orderApiClient.ShowOrderForApproval(id);
if (response.StatusCode == (HttpStatusCode)422)
{
Logger.LogWarning(response.Content);
var responseJson = JObject.Parse(response.Content);
ProcessValidationErrorsFromResponse(response);
}
当我查看response.Content
的值时,发现JSON被截断了。
如果我通过OK响应传递相同的数据对象,那么它将起作用。
protected IHttpActionResult CreateOkResponse<TData>(TData data, string message = "Call was successful")
{
var response = new ResponseObject<TData>(data)
{
Status = "Success",
Message = message
};
return Ok(response);
}
为什么422会截断数据?可能还有其他事情吗?
更新: 这是ShowOrderForApproval的作用:
public async Task<IRestResponse> ShowOrderForApproval(int id)
{
var request = new RestRequest("/api/orders/{id}/approve/")
{
Method = Method.GET,
RequestFormat = DataFormat.Json
};
request.AddUrlSegment("id", id.ToString());
return await RsClient.SendRequestAsync(request, new HttpContextWrapper(HttpContext.Current));
}
RsClient.SendRequestAsync是:
public static Task<IRestResponse> SendRequestAsync(RestRequest request, HttpContextBase context)
{
if (_client == null)
{
_client = Connect();
}
//If null, this is coming from the CI API and we've stored the value in the originating request header
if (context.Session == null)
{
var authHeaderValue = context.Request.Headers["Authorization"];
request.AddHeader("Authorization", "Bearer " + authHeaderValue);
}
else
{
var sessionTokenName = ConfigurationManager.AppSettings["SessionTokenName"];
request.AddHeader("Authorization", "Bearer " + context.Session[sessionTokenName]);
}
return Task.FromResult(_client.Execute(request));
}
更新2: 好的,更多更新。使用Postman,我可以使用422获取所有数据。我们的RsClient使用RestSharp。