Reputation: 8137
Very new to ASP.net MVC and C# in general. Experience with PHP/NodeJS mostly, a little Java.
I have a method in a controller like so:
public ActionResult ImageProcess(string fileName){
string url = "http://myurl.com/images/" + fileName + ".jpg";
//Code to stream the file
}
And when I navigate to it as "http://myurl.com/Home/ImageProcess/12345" I get thrown a 404 error by the process as it's trying to fetch the file.
If I hard-code it like so...
public ActionResult ImageProcess(string fileName){
string url = "http://myurl.com/images/12345.jpg";
//Code to stream the file
}
...It works just fine, returns my processed image as expected.
Why is this happening?
Upvotes: 1
Views: 3550
Reputation: 7490
If you're using the default routes provided for ASP.NET MVC, the fix is simple: change fileName
to id
.
Example:
public ActionResult ImageProcess(string id) {
string url = "http://myurl.com/images/" + id + ".jpg";
}
In the file RouteConfig.cs
you should see something like this:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "YourProject.Controllers" }
);
This is the configuration that tells the framework how to interpret URL strings and map them to method calls. The parameters for these method calls need to be named the same as in the route.
If you want the parameter to be named fileName
, just rename {id}
to {fileName}
in RouteConfig.cs, or create a new route with a new name and defaults above the default route. But, if that's all you're doing, you might as well stick with the default route and name the parameter id
in your action.
Your other option would be to use a query parameter, which would not require any route or variable changes:
<a href="http://myurl.com/Home/ImageProcess?fileName=yourFileName">link text</a>
Look here for a nice tutorial on routing.
Upvotes: 7
Reputation: 3579
Either change the routing value as @johnnyRose already suggested or change the url to a get parameter, that will let the model binding find the fileName attribute. Like this:
http://myurl.com/Home/ImageProcess?fileName=12345
Upvotes: 0