c# - 在一个 Controller 中使用 GUID 作为参数?

标签 c# asp.net asp.net-mvc guid

我的目标是我仍然想使用默认的 asp.net mvc id 但我想像这样在一个 Controller 中使用 Guid

http://example.com/MyController/Index/387ecbbf-90e0-4b72-8768-52c583fc715b

这是我的路线

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

现在我的 Controller

public ActionResult Index(Guid guid)
{
return View();
}

给我错误

The parameters dictionary contains a null entry for parameter 'guid' of non-nullable type 'System.Guid' for method 'System.Web.Mvc.ActionResult Index(System.Guid)'

我猜是因为我在 route 有 ID?如何在一个 Controller 中使用 GUID 作为参数,但在应用程序的其余部分(默认情况下)使用 id

最佳答案

只需将参数名称从 guid 更改为 id:

public ActionResult Index(Guid id)
{
    return View();
}

绑定(bind)操作时,ASP.NET MVC 检查操作方法的类型和名称,并将它们映射到请求提供的参数。由于在路由中使用术语 id,因此您必须相应地命名操作的参数。

关于c# - 在一个 Controller 中使用 GUID 作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363465/

相关文章:

asp.net - 如何使用 ASP.NET 制作一个非常简单的 Web 代理?

asp.net-mvc - LINQ - OrderBy 的动态表达式

c# - 从 Azure Blob 存储返回 PDF 时出现“错误,无法加载 PDF 文档”

c# - 使用结构而不是类的 EntityFramework SqlQuery 失败并出现 ArgumentException

c# - 递归 linq 和这个?

c# - 从 app.config 获取连接字符串

asp.net - 在 Visual Studio 2008 中 - 在 web.config 更改 "takes"之前多久?

regex - 使用电子邮件地址作为用户名的正则表达式?

c# - linq to sql提交更改不起作用

c# - 如何让 BackgroundWorker 返回一个对象