【发布时间】:2015-05-21 14:44:42
【问题描述】:
我创建了一个简单的ApiController whit 3 函数。
- get() // 全部获取
- get(int id) // 通过 id 获取
- getFirst() // 获取列表中的第一个
我有 2 个场景,我会非常感谢一个正确的解释。
1:如果我只实现
get()和get(int id),当我调用api/controller/{id}(id 可选)时,它会完美运行-
2:当我尝试访问
api/controller/function/{id}(id 可选)时,当我拥有 3 个功能时,它不起作用。仅适用于通过 id 获取的功能。您可以在下面看到我遇到的错误。请求无效。 参数字典包含“Practica.Controllers.PersonController”中方法“Practica.Models.Person GetById(Int32)”的不可空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。
API 类:
公共类 PersonController : ApiController { 私人人员[] 列表人员;
public PersonController() {
listPerson = new Person[3];
listPerson[0] = new Person {
id = 1,
firstName = "test",
lastName = "test",
email = "test@gmail.com",
age = 26
};
listPerson[1] = new Person
{
id = 2,
firstName = "test",
lastName = "test",
email = "test@gmail.com",
age = 26
};
listPerson[2] = new Person
{
id = 3,
firstName = "test",
lastName = "test",
email = "test@gmail.com",
age = 26
};
}
public Person GetById(int id) {
try
{
var person = this.listPerson.Where(p => p.id == id).FirstOrDefault();
if (person != null)
{
return person;
}
else {
throw new InvalidOperationException();
}
}
catch (Exception) {
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public Person[] Get()
{
try
{
if (this.listPerson != null)
{
return this.listPerson;
}
else
{
throw new InvalidOperationException();
}
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public Person GetFirst()
{
try
{
if (this.listPerson != null)
{
return this.listPerson.Where(x=>x.Equals(1)).FirstOrDefault();
}
else
{
throw new InvalidOperationException();
}
}
catch (Exception)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
}
WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
就像ApiController 只识别get 和get?id,所以有人可以解释一下为什么以及如何解决这个问题?
谢谢
【问题讨论】:
-
每个函数都可以使用路由属性
-
你到底是什么意思?
-
我的意思是属性路由通过这种方式你可以为控制器内的每个函数指定不同的名称asp.net/web-api/overview/web-api-routing-and-actions/…
-
@Prashant 如果您想发布答案,我会给您积分。谢谢:)
标签: c# api asp.net-web-api routing