C# MVC url 参数未被读取

C# MVC url parameter not being read

总体上 ASP.net MVC 和 C# 非常陌生。主要有 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
}

...效果很好,returns 我处理的图像符合预期。

为什么会这样?

如果您使用为 ASP.NET MVC 提供的默认路由,修复很简单:将 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>

Look here for a nice tutorial on routing.

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

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