【发布时间】:2021-12-12 00:50:00
【问题描述】:
我想编写许多接收对象 ID 的 GET 处理程序,
site.com/controller/Action1/1234
site.com/controller/Action2/1234
site.com/controller/Action3/1234
我想编写一次从数据库中获取复杂对象的代码:
class ComplexObject
{
public string str1 { get; set; }
public string str2 { get; set; }
}
ComplexObject GetFromId(string id)
{
ComplexObject x = Database.GetById(id);
if (x == null)
{
return Http404();
}
return x;
}
然后直接使用对象:
[Route("/[controller]/[action]/{message}")]
[HttpGet]
public string Action1(ComplexObject message)
{
return message.str1;
}
[Route("/[controller]/[action]/{message}")]
[HttpGet]
public string Action2(ComplexObject message)
{
return message.str1;
}
[Route("/[controller]/[action]/{message}")]
[HttpGet]
public string Action3(ComplexObject message)
{
return message.str1;
}
而且我所有的处理程序都只会获取对象,而不必检查 ID 是否正确等。
这怎么可能?
【问题讨论】:
-
我不建议这样做,因为您会将大量工作委托给自定义模型活页夹,这对我来说真的很奇怪。
-
只是想明白,你想写一个endpoint来通过ID和对象名返回任意对象?
-
顺便说一句,所有这些都记录在官方文档中...docs.microsoft.com/en-us/aspnet/core/mvc/advanced/…
-
@Marius 嗨,我想编写许多端点来做不同的事情,但都将使用该对象。想象一下控制汽车的东西。您将有“驾驶”、“停止”和“转弯”,都收到汽车的 ID
标签: c# asp.net-core asp.net-core-mvc model-binding