使用List <>进行C#Web API响应处理

Ray*_*sta 1 c# entity-framework asp.net-web-api

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

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

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

}
Run Code Online (Sandbox Code Playgroud)

感谢一些帮助以及如何正确执行此操作的一些指示.

Amy*_*Amy 5

将您的退货类型更改为IHttpActionResult.

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

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

要返回列表数据,请返回Ok(vs1).

有关更多信息,请参阅文档.

可选:如果您使用的是Swagger或Web Api帮助页面等文档工具,还可以将该[ResponseType(typeof(List<ValueStory>))]属性添加到操作方法中.