C#MVC url参数未被读取

时间:2016-02-11 16:03:49

标签: c# asp.net asp.net-mvc routing asp.net-mvc-routing

一般来说,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
}

...它工作正常,按预期返回我处理过的图像。

为什么会这样?

2 个答案:

答案 0 :(得分:6)

如果您使用为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

答案 1 :(得分:0)

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

http://myurl.com/Home/ImageProcess?fileName=12345
相关问题