Passing a filepath over url - asp.net-mvc-3

I need to pass this filepath over via route to my actionmethod:
<p>#car.Name</p>
so for example #car.ContainerPath is a string of "34_Creating%20Cars%20Forms/Exercise%20Cars/Audi%202010%20Parts%20Reference.pdf"
I need to escape this somehow I think? I would prefer not to send this over url but with a hyperlink I don't see a way not to.
UPDATE:
For additional info, here's the actionmethod it's going to:
public string GetFileZipDownloadUrl(CarViewModel model, string fileContainerPath)
{
string downloadUrl = string.Empty;
downloadUrl = GetFileZipDownloadUrl(model.CarId,fileContainerPath, model.UserId);
return downloadUrl;
}
so I'm sending over for that fileContainerPath paths like this in the url for that #car.ContainerPath param:
"55_Creating Cars Forms/Exercise Cars/Audi Parts Reference.pdf"
so the route url before it's requested looks like this when formed in that hyperlink:
http://Cars/55/55_Creating Cars Forms/Exercise Cars/Audi Parts Reference.pdf/20/Url
My action method just needs to use that path to go get a reference to a file under the hood.

If you want to just get rid of %20 in the url use encoding/decoding like in #Xander's answer. However if any of your data is very dynamic and can have weird characters you should consider adding a Safe() and Unsafe() methods that will strip out all the "Dangerous" characters for url, and then turn it back to original value.

Raw Url:
HttpUtility.UrlEncode(rawurl);
Decode encoded url:
HttpUtility.UrlDecode(encodedurl);
http://msdn.microsoft.com/en-us/library/system.web.httputility.urlencode.aspx
http://msdn.microsoft.com/en-us/library/system.web.httputility.urldecode.aspx

Related

URI within endpoint

I have a URI string inside the request that I am supposed to make. How to extract it and write a proper controller.
markerURI = marker://markerType/markerValue
Request:
POST /books/123/markers/marker://big/yellow
I have written below rest controller for the above request:
#PostMapping("/books/{id}/markers/{markerURI:^marker.*}")
public void assignMarker(
#PathVariable("id") String id,
#PathVariable("markerURI") String markerURI
)
but i'm not able to get markerURI=marker://big/yellow inside markerURI variable. The request show 404 Not found error. Is there any way to do this. It's a requirement so can't do any hacks.
Edit:
markerURI can contain attributes like marker://markerType/markerValue?attr1=val1&attr2=val2
As per https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-requestmapping-uri-templates
You can have your url pattern in below pattern
"/resources/ima?e.png" - match one character in a path segment
"/resources/*.png" - match zero or more characters in a path segment
"/resources/**" - match multiple path segments
"/projects/{project}/versions" - match a path segment and capture it as a variable
"/projects/{project:[a-z]+}/versions" - match and capture a variable with a regex
but your url pattern is defined as a url inside a url, for that I suggest you to use below method and concatenate your result after fetching the values from uri as pathvariable.
#PostMapping("/books/{id}/markers/{marker:[a-z]+}://{markerType:[a-z]+}/{markerValue:[a-z]+}")
public void assignMarker(#PathVariable("id") String id,#PathVariable("marker") String marker,
#PathVariable("markerType") String markerType,
#PathVariable("markerValue") String markerValue) {
String markerUri = "/"+marker+"://"+markerType+"/"+markerValue;
System.out.println(markerUri);
}

How to make Get Request with Request param in Postman

I have created an endpoint that accepts a string in its request param
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression") String expression) {
System.out.println(expression);
// code to validate the input string
}
While sending the request from postman as
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606/Curr_month:Y07608
// lets say this is a valid input
console displays as
Y07607=Curr_month:Y07606/Curr_month:Y07608 Valid
But when i send
https://localhost:8443/validate?expression=Y07607=Curr_month:Y07606+Curr_month:Y07608
//which is also an valid input
console displays as
Y07607=Curr_month:Y07606 Curr_month:Y07608 Invalid
I am not understanding why "+" is not accepted as parameter.
"+" just vanishes till it reaches the api! Why?
I suggest to add this regular expression to your code to handle '+' char :
#GetMapping(value = "/validate")
private void validateExpression(#RequestParam(value = "expression:.+") String expression) {
System.out.println(expression);
// code to validate the input string
}
I didn't find any solution but the reason is because + is a special character in a URL escape for spaces. Thats why it is replacing + with a " " i.e. a space.
So apparently I have to encode it from my front-end
Its wise to encode special characters in a URL. Characters like \ or :, etc.
For + the format or value is %2. You can read more about URL encoding here. This is actually the preferred method because these special characters can sometimes cause unintended events to occur, like / or = which can mean something else in the URL.
And you need not worry about manually decoding it in the backend or server because it is automatically decoded, in most cases and frameworks. In your case, I assume you are using Spring Boot, so you don't need to worry about decoding.

How can I change name of dynamically generated URL in Codeigniter

I'm having dynamic url for my each search result in Codeigniter, but I want to know how can I change my url. For example right now I'm having the url something like this:
www.xyz.com/vendor/vendor_details?iuL80rpoEMxCi89uK6rIyTgqCGuagQ+BUoUnvyBdx09EawMiFfnaB+q3Q8YyBSFwbOVw8+32ZInJrjE2I42teA==
but I want it like this:
www.xyz.com/Delhi/Balaji-Courier-And-Cargo-Bharat-Singh-Market-Opposite-B-7-Petrol-Pump-Vasant-Kunj/011P1238505881A9D9W7_BZDET?xid=RGVsaGkgSW50ZXJuYXRpb25hbCBDb3VyaWVyIFNlcnZpY2VzIEhhbWlsdG9uIFJvYWQ=
here the example
$route['vendor/(:any)/(:any)/(:any)'] = 'vendor/vendor_details/$3';
See this Documentation here: routing
You want to add
www.example.com/city/address/related_id
This Example can help you to get that.
Here are a few routing examples:
$route['journals'] = 'blogs';
A URL containing the word “journals” in the first segment will be remapped to the “blogs” class.
$route[blog/Joe'] = 'blogs/users/34';
A URL containing the segments blog/Joe will be remapped to the “blogs” class and the “users” method. The ID will be set to “34”.
$route['product/(:any)'] = 'catalog/product_lookup';
A URL with “product” as the first segment and anything in the second will be remapped to the “catalog” class and the “product_lookup” method.
$route['product/(:num)'] = 'catalog/product_lookup_by_id/$1';
A URL with “product” as the first segment and a number in the second will be remapped to the “catalog” class and the “product_lookup_by_id” method passing in the match as a variable to the method.

http.NewRequest() decoding my URL input

When using http.NewRequest("GET", url , nil) for URLs that contain a % followed by some number, *example: https://api.deutschebahn.com/freeplan/v1/journeyDetails/356418%252F128592%252F57070%252F90271%252F80%253fstation_evaId%253D8000261) Go will encode the string to a "/" in the url. How can I avoid that?
Explicitly set the RawPath field of the URL struct:
req := http.NewRequest("GET", "https://api.deutschebahn.com/freeplan/v1/journeyDetails/356418%252F128592%252F57070%252F90271%252F80%253fstation_evaId%253D8000261", nil)
req.URL.RawPath = "/freeplan/v1/journeyDetails/356418%252F128592%252F57070%252F90271%252F80%253fstation_evaId%253D8000261"
This functionality is documented for this use case:
Note that the Path field is stored in decoded form: /%47%6f%2f becomes /Go/. A consequence is that it is impossible to tell which slashes in the Path were slashes in the raw URL and which were %2f. This distinction is rarely important, but when it is, code must not use Path directly.
Go 1.5 introduced the RawPath field to hold the encoded form of Path. The Parse function sets both Path and RawPath in the URL it returns, and URL's String method uses RawPath if it is a valid encoding of Path, by calling the EscapedPath method.

Passing date parameters to #url.action via ajax

In my ASP.NET MVC 4 app, I'm using the following JAX code taken from this StackOverflow post to pass Date parameters to a controller but I am getting the following http 404 error: "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Requested URL /myWebApp/myController/myAction/01/01/2014/12/31/2014"
Here the input controls txtFrom and txtTo have the values 01/01/2014 and 12/31/2014 respectively. the issue is that MVC is probably interpreting each date as three different parameters. How can we fix it. I tried replacing $('#txtFrom').val() with $('#txtFrom').val().replace("///g", "_") but it does not work.
window.location.href = '#Url.Action("myAction")/' + $('#txtFrom').val() + '/' + $('#txtTo').val();
Action method:
public ActionResult myAction(string startDate, string endDate)
{
//simple code here to use the input parameters
}
You could either format the date string with Razor
#HttpUtility.UrlEncode(date)
with javascript
encodeURIComponent(date)
or pass the date as ticks (milliseconds since Epoch) instead of the human-readable format.
Edit:
After experimenting with this and a bit of research it seems the slash and %2f encoding causes all kinds of problems. Stick to the millisecond representation for a date and not worry about passing the slash.
window.location.href is not ajax. Its your browser making a HTTP get request to the url. In your case, its not a complete url, but a partial; thus the error. You may try the following for start. Substitute the hardcoded values for dates with your inputs
$.getJSON({‘#Url.Action("myAction")’ + '/', { startDate: ‘1/1/2001’, endData: ‘1/2/2002’ }});
If you want to process any return value; refer to jquery documentation on $.getJSON (http://api.jquery.com/jquery.getjson/)

Resources