我看到這個代碼在書上,是與客戶端創建一個對象(僱員,在這種情況下)提供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);
}
我知道如何工作,但不會下縮寫代碼也適用:
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);
}
?
帶'PUT'動詞的路由'api/employee/{id}'?如果是這樣,你需要'id'參數。 –
@David爲什麼你需要將id作爲參數,如果employee參數已經有相同的賦值? – varevarao
@varevarao也許約定;也許被傳遞的模型沒有定義id。當您更新應該可以通過唯一URI訪問的現有資源時,可能需要符合REST。 –