c# - AttributeRouting 修复两个名为 Id 的参数
问题描述
所以我有一个使用默认值Route
的项目
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
我刚刚遇到了 7 年前在MVC Pro 中描述的情况 提示:不要在路由中使用“id”URL 参数。
他们拥有的解决方案非常棒,但此刻,我不想改变我的整个网站。我希望用Attribute Routing解决我的问题。
但是,我似乎无法让它工作,我收到了一个404 Error
页面。(以防上面的链接不起作用,我将在此处详细描述代码)。
细节
在我的项目中,我使用ViewModels
. 是ViewModel
(非常简单地)定义为:
public class Foo {
public int Id { get; set; }
...
}
我BarController
的如下:
public ActionResult Create(string id) {
if (string.IsNullOrWhiteSpace(id)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
[HttpPost]
public ActionResult Create(string id, Foo viewModel) {
if (string.IsNullOrWhiteSpace(id)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
错误
当我导航到 时/Bar/Create/abc123
,我看到我的表格很好。但是,当我提交表单时,Model.IsValid
是false
. 查看对象的Watch
窗口this.ModelState
,我发现错误消息说
值“abc123”对 ID 无效。
我认为这是因为模型绑定器试图绑定abc123
到具有属性Id
的对象。ViewModel
int
Id
我试过的
到目前为止,这是我尝试在我的 上做的事情Controller
:
[Route("Bar/Create/{aid}", Name = "FooBarRouteName")]
public ActionResult Create(string aid) {
if (string.IsNullOrWhiteSpace(aid)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
[HttpPost]
public ActionResult Create(string aid, Foo viewModel) {
if (string.IsNullOrWhiteSpace(aid)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
现在的问题是当我导航到 时/Bar/Create/abc123
,我得到一个404 Error
页面,甚至无法尝试提交表单。
有人可以指出我正确的方向或找出我做错了什么吗?谢谢!
解决方案
首先确保在基于约定的路由之前启用属性路由,以避免路由冲突。
//Attribute routing
routes.MapMvcAttributeRoutes();
//Convention-based routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
您缺少 POST 操作的路线。
如果使用属性路由,您必须装饰控制器上的所有操作
[HttpGet]
[Route("Bar/Create/{aid}", Name = "FooBarRouteName")] // GET Bar/Create/abc123
public ActionResult Create(string aid) {
if (string.IsNullOrWhiteSpace(aid)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
[HttpPost]
[Route("Bar/Create/{aid}")] // POST Bar/Create/abc123
public ActionResult Create(string aid, Foo viewModel) {
if (string.IsNullOrWhiteSpace(aid)) {
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
...
}
推荐阅读
- python - 越过 sys.excepthook
- google-cloud-platform - 如何在 Cloud Build CI/CD 管道 yaml 脚本或 Cloud Build Triggers 页面中提取实际时间戳
- c# - 如何使用 CSOM 获得分配批准项目?
- java - Minecraft - 使用此代码消失的浮动项目?
- javascript - TensorflowJS:计算多个张量之间的距离或相似度的最佳方法?
- regex - 如何从 $request 中提取请求参数?
- excel - 如何从excel中包含任何值(文件路径)的列中添加多个附件
- android - 找不到无法编译到设备中的错误
- google-cloud-platform - 谷歌云堆栈驱动程序中的正常运行时间检查失败
- docker - Kubernetes:即使在 pod 就绪状态为 true 后,部署也无法推出