【问题标题】:What should my JSON response contain when I have an HTTPException?当我遇到 HTTPException 时,我的 JSON 响应应该包含什么?
【发布时间】:2013-04-04 23:56:54
【问题描述】:

我让用户在以下代码中注册我的应用程序:

        [System.Web.Http.HttpPost]
        [System.Web.Http.AllowAnonymous]
        //[ValidateAntiForgeryToken]
        //public HttpResponseMessage Register(RegisterModel model, string returnUrl)
        public UserProfileDto Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (WebSecurity.UserExists(model.UserName))
                {
                   throw new HttpResponseException(HttpStatusCode.Conflict);
                }
                else
                {
                    // Attempt to register the user
                    try
                    {
                        WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                        WebSecurity.Login(model.UserName, model.Password);

                        InitiateDatabaseForNewUser(model.UserName);

                        FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);

                        var responseMessage = new HttpResponseMessage(HttpStatusCode.Redirect);
                        responseMessage.Headers.Location = new Uri("http://www.google.com");

                        return _service.GetUserProfile(WebSecurity.CurrentUserId);
                    }
                    catch (MembershipCreateUserException e)
                    {
                        throw new HttpResponseException(HttpStatusCode.NotFound);
                    }
                }
            }

            // If we got this far, something failed
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }

我的问题:如果我遇到这些异常之一,我想告诉用户“嘿,该用户名已经存在!”或“哎呀,发生了什么事。我们正在调查。”等客户端,我应该如何处理这个?只需检查标题中的状态并相应地向视图发送内容?

这是否意味着每个可能的错误都应该使用不同的状态码?这似乎是错误的......这让我问 - 我应该将某种与状态相关的数据发送回客户端吗?如果是这样,我的返回类型(在本例中为 UserProfileDto)是否应该包含一个我可以填充但我认为适合我的控制器的“状态”字段?

对不起,我在那里问了一堆......只是想弄清楚如何正确地做到这一点。

【问题讨论】:

    标签: json rest web-applications asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

    ReasonPhrase 的存在是为了提供一个关于错误发生原因的可读描述。如果简单的文字描述不足以将问题传达给最终用户,那么有一些新兴的标准方法可以向用户描述问题。

    application/api-problem+jsonhttps://datatracker.ietf.org/doc/html/draft-nottingham-http-problem-03 application/api-problem+xml

    application/vnd.error+jsonhttps://github.com/blongden/vnd.error application/vnd.error+xml

    【讨论】:

      【解决方案2】:

      我会使用允许您将注册信息或错误消息传递回客户端的模型。

      模型可能类似于:

      public class RegistrationModel
      {
          public UserProfileDto UserProfile { get; set; }
          public ErrorModel Error { get; set; }
      }
      
      public class ErrorModel 
      {
          public string Message { get; set;}
      }
      

      此外,您可能应该返回一个 HttpResponseMessage,它允许您指定您的模型:

      return Request.CreateResponse<RegistrationModel>(HttpStatusCode.Created, MyModel);
      

      【讨论】:

      • 谢谢杰德。认为我的所有模型现在都需要一个“错误”属性似乎很混乱......有替代方案吗?仅仅依靠 HttpStatusCodes 来保证我的模型不会臃肿可以吗?
      • 最终,对你有用的就是你应该做的。我认为在你的模型上有一个错误属性可以让你在客户端快速检查 if(Model.Error!=null) {...} 并且你可以通过响应发送更多关于错误的信息.与其说是臃肿,不如说是灵活性。
      猜你喜欢
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 2014-11-16
      • 1970-01-01
      相关资源
      最近更新 更多