ASP.NET Routing: Formatting the URL string - asp.net

I have implemented a routing functionality successfully in my project (a news website):
Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.MapPageRoute("ndetails", "news/{title}/{id}/", "~/newsdetail.aspx")
End Sub
and I set the URLs like this (databound to a repeater):
href="<%# Page.GetRouteUrl("ndetails", new with { .title= Server.UrlEncode(Eval("Title")), .id= Eval("NewsID")})%>"
The URL produced is like:
/this%20is%20a%20news%20item/89
As can be seen above, the URL part is difficult to read and I would like it to be like:
/this_is_a_news_item/89
I thought of going for a Replace function. But then, since the user creating the news might enter any string, I have to take into account all the other characters that might need to be replaced.
I just wanted to know from an experienced developer, whether going with a long replace function is the way to go, or is there another solution to format my URLs in this rouitng scenario.
Many thanks in advance

AFAIK there is no built in funcitonality in the framework to make url "pretty". You have to implement your own url fo rewriting the title.
In the save of your entities simply use a function that do the replaces that you need (' ' with '_' or example) and then use UrlEncode.
You can also use a Regular expression to do the replacement in one go.

Related

Does Kentico allow query strings with question mark?

I'm trying to migrate my ASPX site to Kentico, and as part of my task I'm migrating URLs. I need to preserve my URL structure, so I need to keep URLs which look like : "foo.com/bar.aspx?pageid=1".
I checked page's "URLs" property tried to use wildcards, some patterns like /bar/{pageid}- /bar/{?pageid?}-, etc but Kentico always replaces question marks.
Is there a way to achieve that via the admin interface?
You don't need to do anything in order to use "foo.com/bar.aspx?pageid=1" url.
Create a page under the root and call it bar, so you'll get a page # foo.com/bar.aspx. Kentico and/or .net does not care what you add to a url after question mark, so foo.com/bar.aspx?pageid=1 will work as well as foo.com/bar.aspx?someparam=sdf, or foo.com/bar.aspx?id=1&p=3&t=3.
You may (or may not) implement some functionality based on query string (e.g. paging), so it will parse query string and act in appropriate way.
By default Kentico UI does not handle adding URL aliases with URL parameters like you show. There is an article on the DevNet for a URL Redirection module which has code you can import into your site to allow you to perform these redirects within the Kentico UI. I'd suggest using this approach.
Unfortunately, I can't share a code sample since it's an article but it also has a link to download the code too. This appears to only be coded for Kentico 8.2 right now but I'm guessing you could do some work to make it work for other versions if you needed.
I think there are few concepts that you are clubbing here. I will start with your line code here
/bar/{pageid} - {pageid} is a positional parameter in Kentico's language if you choose to use dynamic URLS based on patterns. SO if you have a code that relies on pageid parameter to fetch some data then Kentico will pass that value. E.g in case of /bar/420, it will pass pageid as 420 different web parts on your template
/bar/{?pageid?} - This will search for query string parameter "pageid" on the request URL and replace its value here. So if you passed foo.com/bar.aspx?pageid=366, the resulting URL will be /bar/366
The #1 is positional parameter and #2 is the way in which Kentico resolves query string macros.
I hope this clarifies.

One route to handle new url and legacy url

I am using the asp.net routing in a webforms application and I need to map the new url's and the legacy url's to the same route.
localhost/blog/?financial-literacy-efficacy
localhost/blog/financial-literacy-efficacy
The legacy url's have a question mark in front of the query string and the routing /{slug} is not picking it up.
i have tried something like this with no luck
routes.MapPageRoute("blog-slug", _
"blog/?{slug}", _
"~/blogArticles/Default.aspx")
Is this possible?
Thanks in advance.
By default, the routes will not accept anything after the ? as part of the page being routed to since by definition the ? separates the query string from the resource in the URL. One way that might work is
routes.MapPageRoute("blog-slug", _
"blog/", _
"~/blogArticles/Default.aspx")
But the "financial-literacy-efficacy" value will instead be a key since it is ?x not ?slug=x. However, since that is the legacy url, there might already exist some portion of your code that checks keys in query strings as opposed to values since most dynamic webforms legacy urls look soemthing like
blog/?slug=x
And then they check Request.Querystring["slug"]. You would need to provide more information in your question if that causes you trouble.

Symfony2 GenerateURL to a complex route

This seems like the dumbest question ever, but I can't seem to figure it out. I have a page the needs to redirect to a complex route and I can't seem to generate the URL. Redirecting to a simple route is easy enough:
return $this->redirect($this->generateUrl('testnumber'));
However, I want to route to: testnumber/1/question/4. How can I accomplish this incredibly simple task? The only thing I have found in the documentation and Google allows me to add parameters and not just create a complex route. For example:
generateURL('testnumber', array('testid'=>1, 'question'=>4))
makes a URL of /testnumber?testid=1&question=4, which I do not want.
Edit: Yes, I already have the route created in a YML file. I simply cannot generate the URL to link to it.
return $this->redirect($this->generateUrl(???????????),true));
This is my route:
#Route("/testnumber/{testid}/question/{question}", name="testnumber")
The Symfony documentation only shows how to generate a URL to " testnumber/1", I need to generate "testnumber/1/question/4".
For
generateURL('testnumber', array('testid'=>1, 'question'=>4))
to work as you want, your route must look like (example using annotations)
#Route("/testnumber/{testid}/question/{question}", name="testnumber")
If you don't define "testid" & "question" parameters in your route, they'll be added to the query string (appended at the end of the URL as GET paramaters)
generated_route?test_id=X&question=X
Find here more relevent examples.

ASP.NET routing: Literal sub-segment between tokens, and route values with a character from the literal sub-segment

The reason I'm asking is because IIS protects certain ASP.NET folders, like Bin, App_Data, App_Code, etc. Even if the URL does not map to an actual file system folder IIS rejects a URL with a path segment equal to one of the mentioned names.
This means I cannot have a route like this:
{controller}/{action}/{id}
... where id can be any string e.g.
Catalog/Product/Bin
So, instead of disabling this security measure I'm willing to change the route, using a suffix before the id, like these:
{controller}/{action}_{id} // e.g. Catalog/Product_Bin
{controller}/{action}/_{id} // e.g. Catalog/Product/_Bin
But these routes won't work if the id contains the new delimeter, _ in this case, e.g.
// These URL won't work (I get 404 response)
Catalog/Product_Bin_
Catalog/Product/_Bin_
Catalog/Product/__Bin
Why? I don't know, looks like a bug to me. How can I make these routes work, where id can be any string?
Ok, I have a definitive answer. Yes, this is a bug. However, at this point I regret to say we have no plans to fix it for a couple of reasons:
It's a breaking change and could be a very hard to notice one at that.
There's an easy workaround.
What you can do is change the URL to not have the underscore:
{controller}/{action}/_{id}
Then add a route constraint that requires that the ID parameter starts with an underscore character.
Then within your action method you trim off the underscore prefix from the id parameter. You could even write an action filter to do this for you if you liked. Sorry for the inconvenience.
You can use characters that are not allowed for a directory or file name like: *,?,:,",<,>,|.
With ASP.NET MVC if you look at the source they have a hard-coded value for the path separator (/) and to my knowledge cannot be changed.

How to write regex to extract FlickR Image ID From URL?

I'm looking to do do two things, and I am looking to do them in a beautiful way. I am working on a project that allows users to upload flickr photos by simply entering their flickr image URL. Ex: http://www.flickr.com/photos/xdjio/226228060/
I need to:
make sure it is a URL that matches the following format: http://www.flickr.com/photos/[0]/[1]/
extract the following part: http://www.flickr.com/photos/xdjio/[0]/
Now I could very easily write some string methods to do the above but I think it would be messy and love learning how to do these things in regex. Although not being a regex ninja I am currently unable to do the above.
Given an input string with a URL like the one you provided, this will extract the image ID for any arbitrary user:
string input = "http://www.flickr.com/photos/xdjio/226228060/";
Match match = Regex.Match(input, "photos/[^/]+/(?<img>[0-9]+)", RegexOptions.IgnoreCase | RegexOptions.SingleLine);
if(match.Success)
{
string imageID = match.Groups["img"].Value;
}
Breaking it down, we are searching for "photos/" followed by one or more characters that is not a '/', followed by a /, followed by one or more characters that are numbers. We also put the numbers segment into a named group called "img".
thought i would add to this that when using the javascript asp.net validator it doesn't support the grouping name.
the regex to use in this situation would be:
photos/[^/]+/([0-9]+)
thought someone might find this useful

Resources