MVC 和失败 AJAX 调用
MVC and fail AJAX call
我有一个控制器方法:
public async Task SaveRouting(string points, int tripId, decimal totalMileage)
{
if (Request.IsAjaxRequest())
{
//....
await _serviceTrip.UpdateTotalMileageAsync(tripId, totalMileage);
}
else
throw new Exception("Only ajax calls are allowed");
}
所以,正如我们所见,这个方法 returns 任务,所以对客户端没有任何影响。但是,如果出现问题(即 totalMileage 小于或等于 0),我想 return 422 状态代码和包含无效数据的字典,例如:
{ "totalMileage" : "Total mileage should be greater than 0" }
怎么做?
我尝试这样做:
if (totalMileage <= 0)
{
Response.StatusCode = 422; // 422 Unprocessable Entity Explained
}
但是如何描述错误?
如果要在设置Response.StatusCode
后描述错误,则必须通过调用Response.Body.Write(byte[],int, int)
写入http响应的正文。
因此,您可以使用以下方法将 响应消息 转换为字节数组:
public byte[] ConvertStringToArray(string s)
{
return new UTF8Encoding().GetBytes(s);
}
然后像这样使用它:
byte[] bytes = ConvertStringToArray("Total mileage should be greater than 0");
Response.StatusCode = 422;
Response.Body.Write(bytes,0,bytes.Length);
但是您可以使用 ControllerBase
上的扩展方法进一步简化它
我有一个控制器方法:
public async Task SaveRouting(string points, int tripId, decimal totalMileage)
{
if (Request.IsAjaxRequest())
{
//....
await _serviceTrip.UpdateTotalMileageAsync(tripId, totalMileage);
}
else
throw new Exception("Only ajax calls are allowed");
}
所以,正如我们所见,这个方法 returns 任务,所以对客户端没有任何影响。但是,如果出现问题(即 totalMileage 小于或等于 0),我想 return 422 状态代码和包含无效数据的字典,例如: { "totalMileage" : "Total mileage should be greater than 0" }
怎么做? 我尝试这样做:
if (totalMileage <= 0)
{
Response.StatusCode = 422; // 422 Unprocessable Entity Explained
}
但是如何描述错误?
如果要在设置Response.StatusCode
后描述错误,则必须通过调用Response.Body.Write(byte[],int, int)
写入http响应的正文。
因此,您可以使用以下方法将 响应消息 转换为字节数组:
public byte[] ConvertStringToArray(string s)
{
return new UTF8Encoding().GetBytes(s);
}
然后像这样使用它:
byte[] bytes = ConvertStringToArray("Total mileage should be greater than 0");
Response.StatusCode = 422;
Response.Body.Write(bytes,0,bytes.Length);
但是您可以使用 ControllerBase