gpt4 book ai didi

未读取 C# MVC url 参数

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:23 25 4
gpt4 key购买 nike

一般来说,对于 ASP.net MVC 和 C# 来说是非常新的。主要使用 PHP/NodeJS,有一点 Java。

我在 Controller 中有一个这样的方法:

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
}

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

为什么会这样?

最佳答案

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

关于未读取 C# MVC url 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35344174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com