WebAPI 项目的 Repository 类中的这段代码:
public DepartmentRepository()
{
Add(new Department { Id = 0, AccountId = "7.0", DeptName = "Dept7" });
Add(new Department { Id = 1, AccountId = "8.0", DeptName = "Dept8" });
Add(new Department { Id = 2, AccountId = "9.0", DeptName = "Dept9" });
}
...由 Controller 类中的此代码调用:
public Department GetDepartment(int id)
{
Department dept = repository.Get(id);
if (dept == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return dept;
}
...在浏览器中使用:
http://localhost:48614/api/departments/1/
...返回:
<Department xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/DuckbillServerWebAPI.Models">
<AccountId>7.0</AccountId>
<DeptName>Dept7</DeptName>
<Id>1</Id>
</Department>
...对应于 Id == 0 而非 Id == 1 的 Department 实例。
在 REST URI 中传递“0”失败。传递“2”返回 AccountId =“8.0”,传递“3”返回 AccountId =“9.0”
如果“1”转换为“First”,那么给出 Ids 值有什么意义?我可以为它们分配 42、76 等。
更新
回答阿德里安银行:
“你检查过 GetDepartment 调用中 id 的值吗?”
这是输入的内容。因为"http://localhost:48614/api/departments/1/"
它是 1,"http://localhost:48614/api/departments/2/"
它是 2,因为"http://localhost:48614/api/departments/0/"
它是 0,然后抛出一个 NotFound 异常。
“另外,存储库的 Get() 方法中的代码是什么样的?”
存储库获取是:
public Department Get(int id)
{
return departments.Find(p => p.Id == id);
}
更新 2
作为对 Mike Wasson 的回答,这里是 Add 方法:
public Department Add(Department item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId++;
departments.Add(item);
return item;
}
我添加/发布项目的代码(同样,基于 Mike Wasson 的代码)是:
public HttpResponseMessage PostDepartment(Department dept)
{
dept = repository.Add(dept);
var response = Request.CreateResponse<Department>(HttpStatusCode.Created, dept);
string uri = Url.Link("DefaultApi", new { id = dept.Id });
response.Headers.Location = new Uri(uri);
return response;
}