【问题标题】:C# Web API Response Handling using List<>使用 List<> 处理 C# Web API 响应
【发布时间】:2018-01-29 20:19:54
【问题描述】:

我有一个 POST 方法,该方法将返回用户的项目列表,并且由于我对 c# web api 非常陌生,如果 Id 为空、空或无效,我很难设置正确的条件和响应。我尝试过类似的响应,但它不起作用主要是因为这些示例使用 iHttpActionResult 而不是 List

这是我的控制器中的代码,我不确定在我提供的 cmets 上放置什么:

[HttpPost]
public List<ValueStory> UserValueStories ([FromBody] ValueStory valuestory)
//public void UserValueStories([FromBody] ValueStory Id)
{
    if (valuestory.Id == "" || valuestory.Id == null)
    {
       //what code to add to change status code to 400 and to display error message?
    }

    //what code to put if the id is not valid, what status code and what message?


    var valueStoryName = (from vs in db.ValueStories
                          where vs.Id == valuestory.Id
                          select vs).ToList();


    List<ValueStory> vs1 = new List<ValueStory>();
    foreach (var v in valueStoryName)
    {
        vs1.Add(new ValueStory()
        {
            Id = v.Id,
            ValueStoryName = v.ValueStoryName,
            Organization = v.Organization,
            Industry = v.Industry,
            Location = v.Location,
            AnnualRevenue = v.AnnualRevenue,
            CreatedDate = v.CreatedDate,
            ModifiedDate = v.ModifiedDate,
            MutualActionPlan = v.MutualActionPlan,
            Currency = v.Currency,
            VSId = v.VSId
        });
    }
    return vs1.ToList();

}

感谢有关如何正确执行此操作的一些帮助和一些指导。

【问题讨论】:

标签: c# entity-framework asp.net-web-api


【解决方案1】:

将您的返回类型更改为IHttpActionResult。

要返回 400 BAD REQUEST,请返回 BadRequest()。

要返回 404 NOT FOUND,请返回 NotFound()。

要返回您的列表数据,请返回Ok(vs1)。

请参阅documentation 了解更多信息。

可选:如果您使用的是 Swagger 或 Web Api Help Pages 等文档工具,还可以将 [ResponseType(typeof(List&lt;ValueStory&gt;))] 属性添加到您的操作方法中。

【讨论】:

    【解决方案2】:

    如果您真的想保留您的返回数据类型(我认为您不应该这样做,请按照另一个答案中的说明进行操作),那么您可以按照Exception Handling in ASP.NET Web API 中的说明抛出异常:

    要使用特定的 HTTP 代码抛出一个简单的异常,请使用:

    throw new HttpResponseException(HttpStatusCode.NotFound);
    

    要指定消息,您可以执行以下操作:

    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
    {
    Content = new StringContent(string.Format("No product with ID = {0}", id)), ReasonPhrase = "Product ID Not Found"
    }
    throw new HttpResponseException(resp);
    

    【讨论】:

      【解决方案3】:

      需要更新方法以实现该级别的灵活性

      [HttpPost]
      [ResponseType(typeof(List<ValueStory>))]
      public IHttpActionResult UserValueStories ([FromBody] ValueStory valuestory) {
          if (valuestory.Id == "" || valuestory.Id == null) {
             //what code to add to change status code to 400 and to display error message?
             return BadRequest("error message");
          }    
      
          var valueStoryName = (from vs in db.ValueStories
                                where vs.Id == valuestory.Id
                                select vs).ToList();    
      
          var vs1 = new List<ValueStory>();
          foreach (var v in valueStoryName) {
              vs1.Add(new ValueStory() {
                  Id = v.Id,
                  ValueStoryName = v.ValueStoryName,
                  Organization = v.Organization,
                  Industry = v.Industry,
                  Location = v.Location,
                  AnnualRevenue = v.AnnualRevenue,
                  CreatedDate = v.CreatedDate,
                  ModifiedDate = v.ModifiedDate,
                  MutualActionPlan = v.MutualActionPlan,
                  Currency = v.Currency,
                  VSId = v.VSId
              });
          }
          return Ok(vs1);    
      }
      

      【讨论】:

        【解决方案4】:

        根据我对 Web API 的了解,在 POST 方法中,您必须返回 post 调用的结果,而不是(或连同)List。

        最好创建一个新模型来存储数据(列表)和 POST 调用的结果(错误消息和状态代码)。

        根据 ID,您可以添加相应的错误消息和代码。 如果数据无效,可以将数据设为null。

        模型可能看起来像这样。

         class Model{
            string errorMsg,
            string statusCode,
            List<ValueStory> data
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-13
          • 1970-01-01
          • 1970-01-01
          • 2013-10-07
          • 2017-09-28
          • 2023-03-30
          • 2019-09-24
          相关资源
          最近更新 更多