抛出HttpResponseException总是会在客户端中产生StatusCode:500响应

时间:2013-08-11 23:53:48

标签: c# asp.net-mvc-4 exception-handling http-headers

我正在编写一个MSMVC API来处理简单的用户注册。在API中,我希望在传递给控制器​​的数据无效时抛出异常。

    public XmlResult RegisterByEmailAddress(UserModel model)
    {
        var errorResponse = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("Problem"),
            ReasonPhrase = "Problem"
        };
        throw new HttpResponseException(errorResponse);
    }

但是无论我在异常中设置什么,我都只在客户端响应中看到500错误。我正在使用Visual Studio 2012并在本地IIS服务器上以调试模式运行API。

Chrome Dev中的响应实际内容为:

方法:Get,Status:500 Internal Server Error,Type text / html

有谁知道问题可能是什么?

5 个答案:

答案 0 :(得分:3)

我认为,根据您自己的答案和我刚刚做的一些测试,您的控制器是从错误的基类继承的。如果您发布了控制器的其余部分,则可能更容易看到。

所有API控制器都应继承自ApiController

MyController : ApiController

答案 1 :(得分:0)

我在扩展的ExceptionFilterAttribute中做了类似的事情。不确定你是否可以这样做,但想到分享我目前使用的代码。这只是一个样本。因为我还有很多要添加到这个方法中。

public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
    var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
    var controllerName =
        actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
    Logger.LogException(controllerName + ":" + actionName, actionExecutedContext.Exception);
    actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                                         {
                                             ReasonPhrase = YourPhrase
                                         };
}

答案 2 :(得分:0)

好的,经过多次试验和错误后,以下工作正常:

throw new HttpException((int)HttpStatusCode.BadRequest, "Invalid password provided to the Api");

这似乎违背了(我认为)建议在开发Api时抛出HttpResponseException的文档。

答案 3 :(得分:0)

如果你继承ApiController并在构造函数中抛出HttpException - 无论你传递了什么HttpStatusCode,你都会得到内部服务器错误(500)

答案 4 :(得分:0)

如果您从构造函数中抛出异常,或者从构造函数中调用了函数/方法,它也会给出状态500。