2012-06-18 33 views
5

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); 
     } 

    } 

Trả lời

12
context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus()); 
context.Response.Content = new StringContent("Hello World"); 

bạn cũng có khả năng sử dụng các CreateResponse (thêm vào trong RC để thay thế cho lớp generic HttpResponseMessage<T> không còn tồn tại) phương pháp nếu bạn muốn vượt qua đối tượng phức tạp:

context.Response = context.Request.CreateResponse(
    context.Exception.ConvertToHttpStatus(), 
    new MyViewModel { Foo = "bar" } 
); 
+0

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

+0

Bạn có thể kiểm tra câu trả lời cập nhật của tôi. –

+0

Tuyệt vời, tôi đã bỏ lỡ 'using System.Net.Http'. Cảm ơn! – jaffa

Các vấn đề liên quan