8

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?

2
  • 4
    What you want is wrong. 404 is the correct status code here. Commented Jan 7, 2013 at 1:52
  • @SLaks: Agreed, but 400 is the business requirement. They see it as passing a blank ID, same as passing an alphanum string rather than int string. Commented Jan 7, 2013 at 1:58

3 Answers 3

10

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this. This is the answer I went with because of an automated test and documentation harness that we have throwing up "ambiguous method" errors.
4

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.