简体   繁体   中英

C# Web API Response Handling using List<>

I have a POST method which will return the list of items from the user and since I am very new to c# web api, I am having a hardtime putting the right condition and response if the Id is null, empty or invalid. I've tried similar response and it doesn't work mainly because those examples are using iHttpActionResult instead of List<>

here is the code in my controller which I am not sure what to place on the comments I provided:

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

}

Appreciate some help and some directions on how to do this correctly.

Change your return type to IHttpActionResult .

To return a 400 BAD REQUEST, return BadRequest() .

To return a 404 NOT FOUND, return NotFound() .

To return your list data, return Ok(vs1) .

See the documentation for more information.

Optional: If you are using a documentation tool like Swagger or the Web Api Help Pages, also add the [ResponseType(typeof(List<ValueStory>))] attribute to your action method.

If you really want to keep your return data type (which I think you shouldn't, do as stated in the other answer), then you can throw exceptions as described in Exception Handling in ASP.NET Web API :

To throw a simple exception with specific HTTP code use:

throw new HttpResponseException(HttpStatusCode.NotFound);

To specify message you can do as follows:

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

Method would need to be updated to allow for that level of flexibility

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

As per the knowledge I have on Web API, in the POST method you have to return the result of the post call instead(or along with) of List.

Its better to create a new model which will store the data (List) and result of the POST call (error message and status code).

Based on the Id, you can add respective error message and code. In case of invalid data, you can make data as null.

The model may look like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM