0

我需要从我的 asp.net mvc 控制器中抛出一个异常以返回到客户端。

我可以:

throw new HttpResponseException(HttpStatusCode.NotAcceptable);返回状态码。

或者我可以这样做:

throw new HttpRequestException("You must fill the name!");返回消息。

我的问题:是否可以结合这两种解决方案来提供状态代码和消息?

有人认为:

throw new HttpRequestException(HttpStatusCode.NotAcceptable, "Fill the name!");

谢谢。


更新

请注意,这是一个 asp.net MVC 网站,但使用的是 Breeze 框架。当我的验证失败时,我需要抛出一个异常(所以在保存我的更改服务器端之前)。

public class TPBContextProvider : EFContextProvider<BreezeContext>
{

    protected override bool BeforeSaveEntity(EntityInfo entityInfo)  
    {
        ...
        throw new HttpResponseException(HttpStatusCode.Conflict);
4

2 回答 2

3

您是否尝试过返回HttpStatusCodeResult而不是呕吐:

public ActionResult Index()
{
    return new HttpStatusCodeResult(HttpStatusCode.NotAcceptable, "Fill the name!")
}
于 2013-07-15T13:19:32.660 回答
2

我认为这会奏效

  var responseMsg = new HttpResponseMessage(HttpStatusCode.Conflict);
  responseMsg.Content = new StringContent("Custom error message");
  throw new HttpResponseException(responseMsg);
于 2013-07-15T21:44:25.017 回答