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的部门实例。
在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()方法中的代码是什么样的?,”
Repository Get是:
public Department Get(int id)
{
return departments.Find(p => p.Id == id);
}
在回答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;
}
答案 0 :(得分:1)
注意:在评论主题中,存储库类是根据本文改编的:http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
Add方法分配ID,覆盖您发布的任何值。该文章中的存储库类实际上仅用于说明Web API。但在典型的应用程序中,ID可能是主DB密钥,客户端不会在POST中指定ID。但这取决于应用程序。