views:

286

answers:

4

Based on various sources it is apparently impossible to send a path like this "/Content/Scripts/jquery.js" as a parameter to MVC action, because forward slashes are used as parameter delimiters "/" and ASP.NET MVC returns 400 Error.

The only working solution I found so far was to Base64 encode such string, send this as a parameter value and decode it inside the controller action. I encode the path to the JS file like this:

http://localhost/vdir/Services/GetJavaScript/=L3JzaDIwMTAvQ29udGVudC9XaWRnZXRGcmFtZXdvcmsvd2lkZ2V0Lmpz/=aHR0cDovL2xvY2FsaG9zdA==

I need it because I use controller actions that return JavaScriptResult for injecting minified and modified JavaScript into page and I don't want to use http handlers in this case.

The question: Is this really the only way with ASP.NET MVC? Because it doesn't look too userfriendly, not that many users would go watching the page source but anyways... ;)

A: 

Can't you just replace the / with another character, like |? It will still make the URI clean, but not interfere with the routing. If all your scripts are in the same directory, you can just default to it and remove the path from the reference, avoiding the problem entirely.

asbjornu
this could work maybe.
mare
+1  A: 

You could use the "old fashioned" querystring approach:

http://localhost/vdir/Services/GetJavaScript?script=/Content/Scripts/jquery.js

And just have your GetJavaScript method accept a string called script:

public ActionResult GetJavaScript(string script)
Patrick Steele
The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.
mare
You must have something in your routing rules that is causing that error. I created a quick and dirty ASP.NET MVC app to test this before posting and it worked. I just used the default routes. What do your routes look like?
Patrick Steele
As it turns out this does work and it's actually the cleanest way. Just make sure that you have action parameters named the same way as QueryString params. And they don't have to be a part of a MVC route.For instance:routes.MapRoute("GetJavaScriptService", RouteType.Regular, "Services/GetJavaScript", new { controller = "Services", action = "GetJavaScript"}, null);And the action:public JavaScriptResult GetJavaScript(string jsPath) { ... }And the request:virtualdir/GetJavaScript?jsPath=URL_Encoded_JS_pathAnother technique that worked for me was converting params to base64
mare
+1  A: 

Url encode it. It should come out something like:

http://localhost/vdir/Services/GetJavaScript/%2FContent%2FScripts%2Fjquery.js

If that doesn't work, throw it in a query string:

http://localhost/vdir/Services/GetJavaScript?js=%2FContent%2FScripts%2Fjquery.js

HTHs,
Charles

Charlino
URL encoding does not work for ASP.NET MVC, I tried.
mare
+2  A: 

A wildcard mapping would let you pass the path as a route variable. See http://stackoverflow.com/questions/323397/file-path-as-mvc-route-argument