服务器验证 - 响应消息?

Server validation - response message?

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

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

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

注:MVC 4,Visual Studio2010。

这是我的 post 函数:

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

有人建议 BadRequest 是 Http 消息 400:

Equivalent to HTTP status 400. BadRequest indicates that the request could not be understood by the server. BadRequest is sent when no other error is applicable, or if the exact error is unknown or does not have its own error code.

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

我觉得NotFound更合适:

Equivalent to HTTP status 404. NotFound indicates that the requested resource does not exist on the server.

浏览器将其视为错误,因此发送到 jQuery AJAX 对象中的错误处理程序。因此您可以正确处理它,即更新 html 中的一些消息框,让用户知道 server/database 根本不包含 table.[=12 中的该资源或行=]