简体   繁体   中英

Returning custom status code is not working in ASP.Net Web API

I am a newcomer in ASP.Net Web API world. Sorry if this is a foolish question.

I have the following api method -

[Route("api/v1/Location/Create")]
[HttpPost]
public IHttpActionResult Create(Location location)
{
    if (!ModelState.IsValid)
    {
       return StatusCode(HttpStatusCode.BadRequest);
    }

    return Ok();
}


public class Location
{
    public int MCC { get; set; }
    public int MNC { get; set; }
    public int LAC{ get; set; }
    public int CellId { get; set; }
}

If I send a string value from client, it still returns StatusCode 200 .

What I am missing here?

You haven't put any data annotations on your location class. Try it adding [Required] data annotation one of property.

Modify your class as follows-

using System.ComponentModel.DataAnnotations;

public class Location
{
    [Required()]
    public int MCC { get; set; }

    [Required()]
    public int MNC { get; set; }

    [Required()]
    public int LAC{ get; set; }

    [Required()]
    public int CellId { get; set; }
}

当每个[Required][Required]注释时, ModelState.IsValid正在检查数据模型的有效性。

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