IHttpActionResult - 怎么用?

时间:2013-11-12 17:15:06

标签: asp.net asp.net-web-api2

我已经看过使用一些新的IHttpActionResults for OK,NotFound的例子。 我没有看到任何使用Unauthorized()的内容。

我现有的代码如下:

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

3 个答案:

答案 0 :(得分:12)

根据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版本或者做一个pull请求试图让它进入主分支)。


返回500错误的IHttpActionResult相当于:

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

答案 1 :(得分:10)

您可以在此处详细了解Unathorized() 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 :(得分:3)

这是我的自定义消息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
        }
    }    

}