从ASP.NET MVC Web API返回400而不是404

sen*_*ett 5 asp.net-mvc-4 asp.net-web-api

我使用VS2012创建了ASP.NET MVC Web API项目的hello世界:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

向该控制器发出一个get请求会返回一些状态为200的数据XML.到目前为止一切都很好.

当我删除该方法时,如下所示:

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";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我找不到404.我想要的是400坏请求,因为必须提供ID.我怎样才能做到这一点?

Fil*_*p W 10

您不需要保留该Get()方法只是为了抛出错误.将Get by ID方法的签名更改为:

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