【问题标题】:Is it OK to return 404 for this case对于这种情况返回 404 是否可以
【发布时间】:2019-11-14 06:14:44
【问题描述】:

我们有一个 API 请求为一家公司发表评论:

POST http://localhost:4249/api/calendar/comments HTTP/1.1
Host: localhost:4249
Connection: keep-alive
Content-Length: 67
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:4249
X-Requested-With: XMLHttpRequest
Content-Type: application/json

{"CompanyId":"9e21bb54-387e-428a-878b-04cd0f9cc0d3","Text":"company comment text"}

如果目前没有我们想发表评论的公司,我们应该返回404 还是400

另外,如果我们以这种方式重组请求

http://localhost:4249/api/calendar/comments?companyid=9e21bb54-387e-428a-878b-04cd0f9cc0d3
Host: localhost:4249
Connection: keep-alive
Content-Length: 67
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:4249
X-Requested-With: XMLHttpRequest
Content-Type: application/json

{ "Text":"company comment text" }

应该更好吗?

CompanyCompanyComment 的 EF 类是:

public class CompanyComment
{
    [Key]
    public Guid Id { get; set; }

    public DateTime CreatedAt { get; set; }

    [Required]
    public string Text { get; set; }

    public string UserId { get; set; }
    public virtual ApplicationUser User { get; set; }

    [Required]
    public Guid CompanyId { get; set; }
    public virtual Company Company { get; set; }
}

public class Company
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public DateTime Created { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }

    public virtual ICollection<CompanyComment> Comments { get; set; }
}

【问题讨论】:

    标签: json rest api http httpwebrequest


    【解决方案1】:

    对于基于HTTP RFC的第一个问题400代码:

    由于格式错误,服务器无法理解请求 句法。客户端不应该重复请求 修改。

    请注意,虽然 RFC 通常针对 API 谈论“格式错误的语法”,但使用了语义含义,即一个属性的类型与 API 文档中声明的预期属性不匹配,例如如果请求包含 CompanyId 作为整数,则返回 400 是有意义的,因为您期望的是 UUID

    而对于404 它说:

    服务器没有找到任何匹配 Request-URI 的东西。不 指示该状况是暂时的还是 永久的。

    因为实际错误是“未找到给定的公司 ID”,所以 404 更有意义。

    至于第二个问题,RFC 允许两者,因此服务器可以同时接受这两者或其中之一,尽管我觉得奇怪,因为服务器的客户端只接受带有查询参数的 POST 请求。

    我个人倾向于避免在 POST 请求中使用查询参数,因为更容易期望所有参数都包含在有效负载中。但是由于 URL 和查询参数应该定义资源与有效负载定义操作,所以它是有意义的。

    我建议使用一种方法来保持一致性,因此 CompanyId 始终在查询中或始终在有效负载中。

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-10
      • 2015-12-08
      • 2014-07-07
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多