Nazmul Haque
Nazmul Haque

Reputation: 334

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?

Upvotes: 2

Views: 102

Answers (3)

Infinity Challenger
Infinity Challenger

Reputation: 1140

ModelState.IsValid is checking the data model validation when each filed is annotated by [Required].

Upvotes: 1

cagri
cagri

Reputation: 64

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

Upvotes: 2

s.k.paul
s.k.paul

Reputation: 7291

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

Upvotes: 1

Related Questions