I see this code in a book, as an example of creating an object (Employee, in this case) with the client providing the ID:
public HttpResponseMessage Put(int id, Employee employee)
{
if (!list.Any(e => e.Id == id)
{
list.Add(employee);
var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, employee);
string uri = Url.Link("DefaultApi", new { id = employee.Id });
response.Headers.Location = new Uri(uri);
return response;
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
I see how this works, but wouldn't the following abbreviated code work as well:
public HttpResponseMessage Put(Employee employee)
{
if (!list.Any(e => e.Id == employee.Id)
{
list.Add(employee);
var response = Request.CreateResponse<Employee>(HttpStatusCode.Created, employee);
string uri = Url.Link("DefaultApi", new { id = employee.Id });
response.Headers.Location = new Uri(uri);
return response;
}
return Request.CreateResponse(HttpStatusCode.NoContent);
}
?
Your suggested less-verbose solution is not wrong, it just changes the default mechanism for how the ASP.NET Web API looks for the values you are passing in.
id
is a simple type, so the ASP.NET Web API will look in the request URI for the value, whereas Employee
is a complex type so the ASP.NET Web API needs to look in the request body. So if you have a route setup that requires the id
be a part of the URI, then it would make more sense to make the id
be a separate parameter, as it will be picked off the URI automatically.
You can instruct the ASP.NET Web API to look in the request URI by using the [FromUri]
attribute in your parameter, like this:
public HttpResponseMessage Put([FromUri]Employee employee)
{
}
Now if you pass the constituent parts of an Employee
object in the query string of the request, then the ASP.NET Web API will pick out those pieces of information and build an Employee
object from, like this:
http://localhost/api/values/?FirstName=John8&LastName=Doe
Note: I am making up the
FirstName
andLastName
names, but they would need to matchpublic
properties of your model class.
For more information read Parameter Binding in ASP.NET Web API.