Hãy xem xét đoạn mã sau:Cách chuyển nội dung theo phản hồi từ bộ lọc Ngoại lệ trong Asp.net WebAPI?
Vấn đề của tôi là:
1) Tôi dường như không thể đúc các lỗi để HttpContent
2) Tôi không thể sử dụng phương pháp mở rộng CreateContent như thế này doesn' t tồn tại trên context.Response.Content.CreateContent
Ví dụ ở đây dường như chỉ để cung cấp StringContent và tôi muốn để có thể vượt qua các nội dung như một JsobObject: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling
public class ServiceLayerExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Response == null)
{
var exception = context.Exception as ModelValidationException;
if (exception != null)
{
var modelState = new ModelStateDictionary();
modelState.AddModelError(exception.Key, exception.Description);
var errors = modelState.SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage);
// Cannot cast errors to HttpContent??
// var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {Content = errors};
// throw new HttpResponseException(resp);
// Cannot create response from extension method??
//context.Response.Content.CreateContent
}
else
{
context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
}
}
base.OnException(context);
}
}
Xin lỗi xem ở trên liên kết trong bài đăng của tôi. Tôi muốn tạo nội dung của loại JsonObject. – jaffa
Bạn có thể kiểm tra câu trả lời cập nhật của tôi. –
Tuyệt vời, tôi đã bỏ lỡ 'using System.Net.Http'. Cảm ơn! – jaffa