2013-11-12 10 views
9

Я видел примеры использования некоторых новых IHttpActionResults для OK, NotFound. Я ничего не видел, используя Unauthorized().IHttpActionResult - Как использовать?

мой существующий код выглядит следующим образом:

catch (SecurityException ex) 
{ 
    request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message); 
} 

Я хотел бы заменить его следующим образом:

catch (SecurityException ex) 
{ 
    response = Unauthorized(); 
} 

, но я не вижу никакой перегрузки, чтобы передать сведения об исключении.

Кроме того, что такое IHttpActionResult эквивалент ошибки 500?

catch (Exception ex) 
{ 
    response = request.CreateErrorResponse(HttpStatusCode.InternalServerError, 
              ex.Message); 
} 
+0

Я нашел response = InternalServerError (ex); для решения проблемы 500. Я все еще ищу пример Unauthorized, который принимает строковое сообщение. – cdarrigo

ответ

12

Per код для ApiController, есть только два перегруженных для Unauthorized():

/// <summary> 
/// Creates an <see cref="UnauthorizedResult"/> (401 Unauthorized) with the specified values. 
/// </summary> 
/// <param name="challenges">The WWW-Authenticate challenges.</param> 
/// <returns>An <see cref="UnauthorizedResult"/> with the specified values.</returns> 
protected internal UnauthorizedResult Unauthorized(params AuthenticationHeaderValue[] challenges) 
{ 
    return Unauthorized((IEnumerable<AuthenticationHeaderValue>)challenges); 
} 

/// <summary> 
/// Creates an <see cref="UnauthorizedResult"/> (401 Unauthorized) with the specified values. 
/// </summary> 
/// <param name="challenges">The WWW-Authenticate challenges.</param> 
/// <returns>An <see cref="UnauthorizedResult"/> with the specified values.</returns> 
protected internal virtual UnauthorizedResult Unauthorized(IEnumerable<AuthenticationHeaderValue> challenges) 
{ 
    return new UnauthorizedResult(challenges, this); 
} 

Так это выглядит, как будто вы не повезло, если вы не хотите, чтобы изменить себя (вилка самостоятельно версию WebAPI или выполнить запрос на перенос, чтобы попытаться попасть в основную ветку).


IHttpActionResult эквивалент возвращает ошибку 500 заключается в следующем:

/// <summary> 
/// Creates an <see cref="ExceptionResult"/> (500 Internal Server Error) with the specified exception. 
/// </summary> 
/// <param name="exception">The exception to include in the error.</param> 
/// <returns>An <see cref="ExceptionResult"/> with the specified exception.</returns> 
protected internal virtual ExceptionResult InternalServerError(Exception exception) 
{ 
    return new ExceptionResult(exception, this); 
} 
+0

Рад, что это помогло вам, не стесняйтесь проголосовать за ответ. :-) –

9

Вы можете прочитать больше о самовольных() здесь How do you return status 401 from WebAPI to AngularJS and also include a custom message? Если найден другой путь - не бросать исключение и использование HttpResponseMessage в качестве возвращаемый тип вашего контроллера, вы можете сделать это следующим образом:

return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "I am unauthorized IHttpActionResult custom message!")); 

Подробнее о ResponseMessage() здесь http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.responsemessage%28v=vs.118%29.aspx

2

Это мое решение для 500 исключения с пользовательским сообщением (развернутом на здесь: https://stackoverflow.com/a/10734690/654708)

Базового класса для всех контроллеров Web API

public abstract class ApiBaseController : ApiController 
{ 
    protected internal virtual IHttpActionResult InternalServerError(Exception ex, string message = null) 
    { 
     var customMsg = String.IsNullOrWhiteSpace(message) ? "" : String.Format("Custom error message : {0}. ", message); 
     var errorMsg = String.Format("{0}{1}", customMsg, ex); 
     return new InternalServerErrorWithMessageResult(errorMsg); 
    } 
} 

public class InternalServerErrorWithMessageResult : IHttpActionResult 
{ 
    private readonly string message; 

    public InternalServerErrorWithMessageResult(string message) 
    { 
     this.message = message; 
    } 

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) 
    { 
     var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) 
         { 
          Content = new StringContent(message) 
         }; 
     return Task.FromResult(response); 
    } 
} 

Примеры контроллеров Web API

public class ProductController : ApiBaseController 
{ 
    public IHttpActionResult GetProduct(int id) 
    { 
     try 
     { 
      var product = productService.GetProduct(id); 
      return Ok(product); // 200 w/ product 
     } catch(Exception ex) 
     { 
      //return InternalServerError(ex); // Uses default InternalServerError 
      return InternalServerError(ex, "My custom message here"); // Uses custom InternalServerError 
     } 
    }  

} 

 Смежные вопросы

  • Нет связанных вопросов^_^