cda*_*igo 9 asp.net asp.net-web-api2
我已经看到了使用一些新的IHttpActionResults for OK,NotFound的例子.我还没有看到任何使用Unauthorized().
我现有的代码如下:
catch (SecurityException ex)
{
request.CreateResponse(HttpStatusCode.Unauthorized, ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
我想用这个替换它:
catch (SecurityException ex)
{
response = Unauthorized();
}
Run Code Online (Sandbox Code Playgroud)
但我没有看到任何超载传递异常细节.
还有,IHttpActionResult相当于返回500错误?
catch (Exception ex)
{
response = request.CreateErrorResponse(HttpStatusCode.InternalServerError,
ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
Kar*_*son 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);
}
Run Code Online (Sandbox Code Playgroud)
所以看起来你运气不好,除非你想自己做出改变(分叉你自己的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);
}
Run Code Online (Sandbox Code Playgroud)
小智 10
您可以在此处阅读有关Unathorized()的更多信息. 如何将状态401从WebAPI返回到AngularJS并包含自定义消息? 如果找到另一种方法 - 没有抛出异常并使用HttpResponseMessage作为控制器的返回类型,你可以这样做:
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "I am unauthorized IHttpActionResult custom message!"));
Run Code Online (Sandbox Code Playgroud)
有关ResponseMessage()的更多信息,请访问 http://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.responsemessage%28v=vs.118%29.aspx