【问题标题】:Server validation - response message?服务器验证 - 响应消息?
【发布时间】:2017-06-02 00:58:00
【问题描述】:

我正在使用 C# 和 HttpResponseMessage 对服务器验证进行编码。我需要使用某些消息将响应发送回客户端,即发送的数据无效。我应该从这个列表中选择哪个响应代码?

https://msdn.microsoft.com/en-us/library/system.net.httpstatuscode(v=vs.110).aspx

我是否也可以自定义消息,以便我知道哪个字段获得了无效数据?

注意:MVC 4,Visual Studio 2010。

这是我的帖子功能:

// POST api/Default1
    [HttpPost]
    public HttpResponseMessage PostUserProfile(HttpRequestMessage  req)
    {
        UserProfile up = new UserProfile();
        string jsonContent = req.Content.ReadAsStringAsync().Result;

        if (ModelState.IsValid)
        {
            up = JsonConvert.DeserializeObject<UserProfile>(jsonContent);
            if (up.userName.Length <= 50 &&
                up.email.Length <= 60)
            {

                db.UserProfiles.Add(up);
                db.SaveChanges();

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, up);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = up.UserId }));
                return response;
            }
            else 
            {
                // finish the server validation
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError, up);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = up.UserId }));
                return response;
            }
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

【问题讨论】:

  • 400(错误请求)就是其中之一。请注意,ModelState.IsValid 始终为真,因为您根本没有使用模型绑定。另外你真的应该use the built-in model binding capabilities of MVC
  • req.CreateResponse(...) 应该可以解决您的问题。您可以使用您喜欢的任何内容进行响应,包括带有无效字段的 JSON 以及对究竟是什么错误以及如何修复它的解释。为此,您最好创建一个包含 string ErrorMessage 等属性的新类,并将 .CreateResponse(...) 作为参数传递到内部。
  • 仅供参考,我会返回代码 400-Bad request
  • BadRequest - 404

标签: c# asp.net ajax model-view-controller httpresponse


【解决方案1】:

有人建议 BadRequest 是 Http 消息 400:

相当于 HTTP 状态 400。BadRequest 表示服务器无法理解该请求。如果没有其他错误适用,或者确切的错误未知或没有自己的错误代码,则会发送 BadRequest。

我认为它不适合这种情况,因为浏览器不会将其视为错误,就好像我将 OK 消息发送回客户端一样。

我觉得NotFound更合适:

相当于HTTP状态404。NotFound表示请求的资源在服务器上不存在。

浏览器将其视为错误,因此将其发送到 jQuery AJAX 对象中的错误处理程序。所以您可以正确处理它,即更新 html 中的一些消息框,让用户知道服务器/数据库根本不包含该资源或表中的行。

【讨论】:

    猜你喜欢
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    相关资源
    最近更新 更多