Asp.net MVC 5 使控制器动作接受剩余类型参数

Asp.net MVC 5 make controller action to accept rest type parameters

我有一个 ASP.NET MVC5 应用程序,我在其中一个控制器中编写了一个新的控制器操作。

我有一个场景,我想从不同的应用程序 (React) 调用这个新的控制器操作。

下面是我的新控制器动作。

public async Task<ActionResult> NewAction(int Id)
{
    var project = await _repository.GetProjectFromIdAsync(Id);
    if (project == null) return HttpNotFound();
    return RedirectToAction("ExistingAction", new { id = project.Id });
}

我可以用这个 url 成功调用操作 - https://myapplicationlink/ControllerName/NewAction?Id=30

但我想调用休息类型 url 的操作,例如 https://myapplicationlink/ControllerName/NewAction/30

但是当我执行此操作时出现错误

The parameters dictionary contains a null entry for parameter 'Id'of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] NewAction(Int32)'

如何使操作接受休息类型URL?

路由模板占位符中的参数名称区分大小写。

您有 Id (大写 I) 而模板为 id (小写).

这与 {controller}/{action}/{id} 路由模板不匹配

重命名参数以匹配路由模板Task<ActionResult> NewAction(int id) { ....

public async Task<ActionResult> NewAction(int id) {
    var project = await _repository.GetProjectFromIdAsync(id);
    if (project == null) return HttpNotFound();
    return RedirectToAction("ExistingAction", new { id = project.Id });
}

首先,检查是否配置了路由{controller}/{action}/{id}

然后将 Id 参数名称重命名为 id