未读取 C# MVC URL 参数

本文关键字:URL 参数 MVC 读取 | 更新日期: 2023-09-27 18:34:09

对于

MVC和C#来说 ASP.net 非常新。主要有PHP/NodeJS的经验,有点Java。

我在控制器中有一个这样的方法:

public ActionResult ImageProcess(string fileName){
  string url = "http://myurl.com/images/" + fileName + ".jpg";
  //Code to stream the file
}

当我导航到它作为"http://myurl.com/Home/ImageProcess/12345"时,我在尝试获取文件时被进程抛出 404 错误。

如果我像这样硬编码它...

public ActionResult ImageProcess(string fileName){
  string url = "http://myurl.com/images/12345.jpg";
  //Code to stream the file
}

。它工作得很好,按预期返回我处理后的图像。

为什么会这样?

未读取 C# MVC URL 参数

如果您使用的是为 MVC 提供的默认路由 ASP.NET 则修复很简单:将fileName更改为 id

例:

public ActionResult ImageProcess(string id) {
  string url = "http://myurl.com/images/" + id + ".jpg";
}

在文件RouteConfig.cs中,您应该看到如下所示的内容:

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

这是告诉框架如何解释 URL 字符串并将其映射到方法调用的配置。这些方法调用的参数需要与路由中的参数相同。

如果您希望将参数命名为 fileName ,只需在 RouteConfig.cs 中将{id}重命名为 {fileName},或者使用新名称和默认值在默认路由上方创建新路由。但是,如果这就是您正在执行的全部操作,那么不妨坚持使用默认路由,并在操作中将参数命名为id

您的另一个选择是使用查询参数,该参数不需要任何路由或变量更改:

<a href="http://myurl.com/Home/ImageProcess?fileName=yourFileName">link text</a>

在这里查找有关路由的精彩教程。

按照@johnnyRose已经建议的那样更改路由值,或者将 url 更改为 get 参数,这将使模型绑定找到 fileName 属性。喜欢这个:

http://myurl.com/Home/ImageProcess?fileName=12345