Mvc 3 - Controller as image handler, how to pass a path?
I am trying to use a controller as an image handler, but how do i pass in a path to it?
Right now it looks like this (works for images without a path):
public void GetImage(string parameter)
{
var imageHandler = UnityGlobalContainer.Container.Resolve<IImageHandler>();
imageHandler.ProcessRequest(parameter);
}
But if i try to send in the path folder1\folder2\folder3\picture.jpg then it fails.
@Html.ActionLink("Show", "GetImage", "Utility", new { parameter = @"folder1\folder2\folder3\picture.jpg" }, new { })
produces this: http://localhost开发者_如何学JAVA:58359/Utility/GetImage/folder1%5Cfolder2%5Cfolder3%5Cpicture.jpg
and that leads to: HTTP Error 400 - Bad Request.
How can i pass in a path to the controller using the normal mvc approach? (I am using backward slashes and not forward slashes) I have also tested using HttpUtility.UrlEncode on the parameter.
According to your code: The produced link in the html page should be: http://localhost:58359/Utility/GetImage?parameter=folder1%5Cfolder2%5Cfolder3%5Cpicture.jpg and the parameter variable should be correctly set to "folder1\folder2\folder3\picture.jpg" in the action method.
Notice that you might be vulnerable to directory traversal here.
In .NET 4.0 beta 2, the CLR team has offered a workaround.
Add this to your web.config file:
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
</schemeSettings>
</uri>
This causes the Uri class to behave according to the RFC describing URIs, allowing for slashes to be escaped in the path without being unescaped. The CLR team reports they deviate from the spec for security reasons, and setting this in your .config file basically makes you take ownership of the additional security considerations involved in not unescaping the slashes.
Can you not just decode the parameter?
http://msdn.microsoft.com/en-us/library/6196h3wt.aspx
Instead of calling the filename parameter 'parameter', and defining it in your route, call it 'filename' and DON'T define it in your route.
Your action code will be the same, but the filename will stop being part of the route and just be an ordinary URL parameter.
If you're afflicted by this season's fashion for disliking URL parameters, then you might find this repugnant, but that's just fashion and can safely be ignored.
Personally, I wouldn't pass paths like this into a web app, because I would be absolutely paranoid about creating traversal threats by mistake - I only ever pass in path-free filenames, validate them against a list and then fetch the file.
精彩评论