sennett
sennett

Reputation: 8424

Returning 400 rather than 404 from ASP.NET MVC Web API

I have created the hello world of ASP.NET MVC web API projects using VS2012:

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

Issuing a get request to that controller returns some XML of the data with status 200. All good so far.

When I remove that method, like this:

public class ValuesController : ApiController
{
    // GET api/values
    //public IEnumerable<string> Get()
    //{
    //    return new string[] { "value1", "value2" };
    //}

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

I then get a 404 not found. What I want is a 400 bad request, because an ID must be provided. How can I achieve this?

Upvotes: 7

Views: 8676

Answers (3)

Evandro Pomatti
Evandro Pomatti

Reputation: 15094

You can also use Action Return types if you don't want to import extra packages for the exceptions.

Instead of throwing an exception you do return a new BadRequestResult instance. Mind the return Action type as well that must be declared.

using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("/api/yourtype")]
public class ValuesController : ControllerBase
{
    public ActionResult Get()
    {
        // 400
        return new BadRequestResult();
    }

    public ActionResult<YourType> Get(int id)
    {
        // 404
        return NotFound();

        // 200
        return Ok(object);
    }
}

Upvotes: 1

Filip W
Filip W

Reputation: 27187

You don't need to keep the Get() method just to throw an error. Change the signature of your Get by ID method to:

public string Get(int? id = null)
{
    if (id == null) throw new HttpResponseException(HttpStatusCode.BadRequest);
    return "value";
}

Upvotes: 10

sennett
sennett

Reputation: 8424

One way is to include the method, but throw an exception instead:

public class ValuesController : ApiController
{
    // GET api/values
    public void Get()
    {
        throw new HttpResponseException(HttpStatusCode.BadRequest);
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }
}

Upvotes: 4

Related Questions