Question

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

?

Was it helpful?

Solution 2

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 and LastName names, but they would need to match public properties of your model class.


For more information read Parameter Binding in ASP.NET Web API.

OTHER TIPS

If your route/api method for PUT is defined as api/employee/{id}, then you'll need id passed in. However, if your Employee object already has the ID, then you could just have a route of api/employee for the PUT verb and just accept the Employee object like your second example shows.

From an example for Web API, the documentation states:

By default, the ASP.NET Web API framework takes simple parameter types from the route and complex types from the request body.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top