2013-01-07 21 views
5

ho creato il mondo ciao di progetti web API ASP.NET MVC utilizzando VS2012:Tornando 400 piuttosto che 404 da ASP.NET MVC Web API

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

emissione una richiesta GET a tale controller ritorna qualche XML i dati con stato 200. Tutto bene finora.

Quando rimuovo questo metodo, in questo modo:

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

Allora ottengo un 404 non trovato. Quello che voglio è una 400 cattiva richiesta, perché deve essere fornito un ID. Come posso raggiungere questo obiettivo?

+2

Quello che vuoi è sbagliato. 404 è il codice di stato corretto qui. – SLaks

+0

@SLaks: concordato, ma 400 è il requisito aziendale. Lo vedono passare un ID vuoto, come passare una stringa alfanum piuttosto che una stringa int. – sennett

risposta

8

Non è necessario per mantenere il metodo Get() solo per gettare un errore. Cambia la firma del tuo metodo Get by ID a:

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

Grazie per questo. Questa è la risposta che ho seguito a causa di un test automatico e di una documentazione che abbiamo lanciato errori "metodo ambiguo". – sennett

4

Un modo è quello di includere il metodo, ma un'eccezione invece:

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