[英]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");
}
因此,正如我們所看到的,此方法返回Task,因此對客戶端沒有任何影響。 但是,如果出現問題(例如totalMileage小於或等於0),我想返回422狀態代碼和帶有無效數據的字典,例如:{“” totalMileage“:”總里程數應大於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
擴展方法進一步簡化此操作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.