当我遇到HTTPException时,我的JSON响应应该包含什么?

时间:2013-04-04 23:56:55

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

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

        [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)是否包含我可以填充的“状态”字段,但是我觉得在我的控制器中是合适的?

抱歉,我在那里问了一堆...只是想弄清楚如何做到这一点。

2 个答案:

答案 0 :(得分:1)

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

application/api-problem+json http://tools.ietf.org/html/draft-nottingham-http-problem-03 application/api-problem+xml

application/vnd.error+json https://github.com/blongden/vnd.error application/vnd.error+xml

答案 1 :(得分:0)

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

模型可能类似于:

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