Ran*_*all 1 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
}
Run Code Online (Sandbox Code Playgroud)
当我以" 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
}
Run Code Online (Sandbox Code Playgroud)
...它工作得很好,按预期返回我处理过的图像.
为什么会这样?
如果您使用为ASP.NET MVC提供的默认路由,则修复很简单:更改fileName为id.
例:
public ActionResult ImageProcess(string id) {
string url = "http://myurl.com/images/" + id + ".jpg";
}
Run Code Online (Sandbox Code Playgroud)
在文件中RouteConfig.cs你应该看到这样的东西:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "YourProject.Controllers" }
);
Run Code Online (Sandbox Code Playgroud)
这是告诉框架如何解释URL字符串并将它们映射到方法调用的配置.这些方法调用的参数需要与路径中的参数命名相同.
如果你希望被命名的参数fileName,只需重命名{id}以{fileName}在RouteConfig.cs,或创建一个新的名称,默认的缺省路由之上的新途径.但是,如果这就是你正在做的事情,你可以坚持使用默认路线并id在你的行动中命名参数.
您的另一个选择是使用查询参数,该参数不需要任何路由或变量更改:
<a href="http://myurl.com/Home/ImageProcess?fileName=yourFileName">link text</a>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1563 次 |
| 最近记录: |