Routing RouteValueDictionary url as second item problem - c#

I have a problem with send URL as RouteValue item and get GetVirtualPath with one`s parameter.
var parameters = new RouteValueDictionary {
{ CommonUrl.UrlParameters.AnyString, "ItISAnyString"},
{CommonUrl.UrlParameters.ReturnUrl, "test/myPage/Index"}
};
And get URL with this parameters:
RouteTable.Routes.GetVirtualPath(null, anyRouteName, **parameters**).VirtualPath
So I get URL like http://localhost/ItISAnyString/test/myPage/Index
System haven`t recognized this page and sad 404.
But if I manually do something like this
http://localhost/ItISAnyString/test$myPage$Index
All work fine.
I think should exist better way to resolve this problem.
Edit
I found that for this Route dont exist any RouteValueDictionary. I think that routing dont undestend second parameter if there is more that one '/' symbol. So I will create it and see what hapens.
Edit
My college sad that I have to encode URL when send it as parameter.
Ok, I did it.
But now I have 400 error.
It`s a bit strange, as for me.

Problem was in the mapping pattern.
I have just added {*} pattern to the route maps.
Now my global.asax code:
routes.MapPageRoute(RouteName.Security.TestOne,
Test,
"~/Web/Pages/Test/test.aspx", true);
public static string Test = String.Format("{0}/{1}/{2}/{3}",
"Test",
"Testconfirm",
"{" + CommonUrl.UrlParameters.FirstParam+ "}",
"{*****" + CommonUrl.UrlParameters.Url + "}");
This concept name is "Handling a Variable Number of Segments in a URL Pattern"
http://msdn.microsoft.com/en-us/library/cc668201.aspx

Related

Routing: how do I redirect to a url when a parameter is missing?

I have routes like this:
example.com/{category}/articles.
There isn't a route for
example.com/{category}
example.com/
I want to redirect all that traffic to
example.com/{category}/articles with a default value.
I've read that I can use default values with a RouteValueDictionary:
routes.MapPageRoute("ArticlesAll", "{category}/articles/", "~/ArticlesPage.aspx", false, new RouteValueDictionary { { "category", "cats" } });
But that doesn't do any redirecting.
Would I need another route to forward to the one above or is there a more efficient way of doing this?
What you are asking is a bit unclear, but let me offer what I usually do.
If you are trying to make it so that two similar links can be written, for example www.example.com/read/penguin/article/ and www.example.com/read/panda/article. I would just write the whole string / URL with a variable in the middle:
private string destination = "penguin";
private string url = "www.example.com/read/" + destination + "/article/";
void Test () {
destination = "lion";
text.URL = url;
}
Sorry, I may have made gramatical mistakes in my code, but I hope you get the point. I may have completely misunderstood you though, so clarification would be appreciated.
You can setup these two routes:
routes.MapPageRoute("ArticlesAll", "{category}/articles/{*value}", "~/ArticlesPage.aspx");
routes.MapPageRoute("CatchAll", "{*value}", "~/ArticlesPage.aspx");
to catch anything and redirect to your desired page. I just assumed where you want to lead your users, change the aspx part as needed. Keep in mind that you can use {value} to access the whatever the user wrote.
For example if they wanted to navigate to dogs and you wanted to redirect to dogs/articles/ArticlesPage.aspx, you should use:
routes.MapPageRoute("CatchAll", "{*value}", "~/{value}/articles/ArticlesPage.aspx");
EDIT
If you want to actually redirect to the new URL and not just serve up the right page, you can use the CatchAll route to redirect to a page (say Redirect.aspx) that's sole purpose is to parse data from the RouteData object, construct the new URL and Redirect.

Redirect any incoming URLs with diacritics to equivalent with no diacritics

How does one implement URL redirecting for URLs with accents? I'd like all potential URL requests with accents to be rewritten without the accent. This is for client names on a French language site. Users should be typing the name without the accent, but should they not do so then I'd like them to land on the correct page either way.
Example
User enters: www.mysite.fr/client/andré ==> user is redirected towww.mysite.fr/client/andre
The resource identifier (clientName) in the database is stored without the accent. Here's my RouteConfig.cs :
routes.MapRoute(
name: "ClientDetails",
url: "client/{clientName}",
defaults: new { controller = "Client", action = "ClientDetails" }
I understand that there are various methods for removing accents on a string. And yes, this would allow me to remove accents from the received URL parameter within the Controller method. However, I would like to be consistent, so that users always see URLs displayed without accents. Therefore, how do I implement redirecting URLs throughout my web application? Is there an easy way to do this in RouteConfig.cs or Web.config ?
I think you mean Redirect and not Rewrite given that Rewrite would mean that the URL stays the same, and you display the intended content (which I think is what you don't want).
The strategy that I think you want, can be implemented by creating a custom route constraint that matches everything that has an any special chars on it.
Make this custom route to be the first thing to be evaluated in your route table, and map this custom route to a "RedirectController" (that you will create) that takes care of removing the special chars from the URL and redirecting the user to a URL with no special chars
At the beginning of every request, you can make this check to perform a redirect. In your Global.asax.cs file, include the following...
protected void Application_BeginRequest()
{
var originalUri = HttpContext.Current.Request.Url;
var finalUri = new UriBuilder(originalUri);
finalUri.Path = RemoveAccents(
originalUri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped)
);
// Check if the URL has changed
if (!originalUri.Equals(finalUri.Uri))
{
HttpContext.Current.Response.Redirect(finalUri.Uri.ToString(), true);
HttpContext.Current.Response.End();
}
}
You might also want to add another line for finalUri.Query and UriComponents.Query. For RemoveAccents, I tried the following code but you can use what you'd like:
public string RemoveAccents(string input)
{
return Encoding.UTF8.GetString(Encoding.GetEncoding(1251).GetBytes(input));
}

How to get full url from dotnetnuke

If I use this:
Request.Url.AbsoluteUri
I get full url like:
http://localhost/mysite/Default.aspx?TabID=269&OTHER-parameters
But I don't want this thing with TabID I need friendly url so if I use:
DotNetNuke.Entities.Tabs.TabController.CurrentPage.FullUrl;
I get
http://localhost/mysite/something/en-us/generatethings.aspx
But with this I don't get parameters :(
How to get full friendly complete url from dnn with all parameters?
Unfortunately, there isn't an easy way to get the current URL within DNN, because the URL gets rewritten before it gets to your module.
What we'll typically do is regenerate the URL, using Globals.NavigateURL. You can use DotNetNuke.Common.Utilities.UrlUtils.GetQSParamsForNavigateURL to get all of the query string parameters from the current URL.
So, you'd end up with something like this:
var currentUrl = Globals.NavigateURL(
this.TabId,
this.Request.QueryString["ctl"],
UrlUtils.GetQSParamsForNavigateURL());
I think this will get you what you want
string url = HttpContext.Current.Request.Url.Scheme + "://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl;
`string url = TabController.CurrentPage.FullUrl;`
this should give you the user friendly url

ASP.NET Site Redirection help

I am following the code over here https://web.archive.org/web/20211020203216/https://www.4guysfromrolla.com/articles/072810-1.aspx
to redirect http://somesite.com to http://www.somesite.com
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (Request.Url.Authority.StartsWith("www"))
return;
var url = string.Format("{0}://www.{1}{2}",
Request.Url.Scheme,
Request.Url.Authority,
Request.Url.PathAndQuery);
Response.RedirectPermanent(url, true);
}
How can I use this code to handle situations where http://abc.somesite.com should redirect to www.somesite.com
I'd suggest the best way to handle this would be in the dns record, if you have control of it.
If you don't know what the values will be ahead of time, you can use substring with indexof for the Url path to parse out the value you want and replace it.
If you do know what it is ahead of time, you can always just do Request.Url.PathAndQuery.Replace("abc", "www");
You can also do a dns check as #aceinthehole suggested after you have parsed what you need to make sure you haven't made any mistakes.
assuming you have a string like http://abc.site.com and you want to turn abc into www then you could do something like.
string pieceToReplace = Request.Url.PathAndQuery.substring(0, Request.Url.PathAndQuery.IndexOf(".") + 1);
//here I use the scheme and entire url to make sure we don't accidentally replace an "abc" that belongs later in the url like in a word "GHEabc.com" or something.
string newUrl = Request.Url.ToString().Replace(Request.Url.Scheme + "://" + pieceToReplace, Request.Url.Scheme + "://www");
Response.Redirect(newUrl);
p.s. I don't remember if the Request.Url.Scheme already has the "://" in it or not so you will need to edit accordingly.
I don't think you can do it without access to the DNS. It sounds like you need a wildcard DNS entry:
http://en.wikipedia.org/wiki/Wildcard_DNS_record
Along with IIS configured without host headers (IP only). Then you can use code similar to the above to do what you want.
if (!Request.Url.Host.StartsWith ("www") && !Request.Url.IsLoopback)
Response.Redirect('www.somesite.com');
Perhaps tighten it up some to prevent wwww.somesite.com from getting through. Anything that starts with www including wwwmonkeys.somesite.com would get through the above check. It is just an example.
asp.net mvc: How to redirect a non www to www and vice versa

How to get the URL of the current page in C# [duplicate]

This question already has answers here:
Get URL of ASP.Net Page in code-behind [duplicate]
(10 answers)
Closed 9 years ago.
Can anyone help out me in getting the URL of the current working page of ASP.NET in C#?
Try this :
string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx
string host = HttpContext.Current.Request.Url.Host;
// localhost
You may at times need to get different values from URL.
Below example shows different ways of extracting different parts of URL
EXAMPLE: (Sample URL)
http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
CODE
Response.Write("<br/>Host " + HttpContext.Current.Request.Url.Host);
Response.Write("<br/>Authority: " + HttpContext.Current.Request.Url.Authority);
Response.Write("<br/>Port: " + HttpContext.Current.Request.Url.Port);
Response.Write("<br/>AbsolutePath: " + HttpContext.Current.Request.Url.AbsolutePath);
Response.Write("<br/>ApplicationPath: " + HttpContext.Current.Request.ApplicationPath);
Response.Write("<br/>AbsoluteUri: " + HttpContext.Current.Request.Url.AbsoluteUri);
Response.Write("<br/>PathAndQuery: " + HttpContext.Current.Request.Url.PathAndQuery);
OUTPUT
Host: localhost
Authority: localhost:60527
Port: 60527
AbsolutePath: /WebSite1test/Default2.aspx
ApplicationPath: /WebSite1test
AbsoluteUri: http://localhost:60527/WebSite1test/Default2.aspx?QueryString1=1&QueryString1=2
PathAndQuery: /WebSite1test/Default2.aspx?QueryString1=1&QueryString2=2
You can copy paste above sample code & run it in asp.net web form application with different URL.
I also recommend reading ASP.Net Routing in case you may use ASP Routing then you don't need to use traditional URL with query string.
http://msdn.microsoft.com/en-us/library/cc668201%28v=vs.100%29.aspx
Just sharing as this was my solution thanks to Canavar's post.
If you have something like this:
"http://localhost:1234/Default.aspx?un=asdf&somethingelse=fdsa"
or like this:
"https://www.something.com/index.html?a=123&b=4567"
and you only want the part that a user would type in then this will work:
String strPathAndQuery = HttpContext.Current.Request.Url.PathAndQuery;
String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(strPathAndQuery, "/");
which would result in these:
"http://localhost:1234/"
"https://www.something.com/"
if you just want the part between http:// and the first slash
string url = Request.Url.Host;
would return stackoverflow.com if called from this page
Here's the complete breakdown
the request.rawurl will gives the content of current page
it gives the exact path that you required
use HttpContext.Current.Request.RawUrl
If you want to get
localhost:2806
from
http://localhost:2806/Pages/
then use:
HttpContext.Current.Request.Url.Authority
a tip for people who needs the path/url in global.asax file;
If you need to run this in global.asax > Application_Start and you app pool mode is integrated then you will receive the error below:
Request is not available in this context exception in
Application_Start.
In that case you need to use this:
System.Web.HttpRuntime.AppDomainAppVirtualPath
Hope will help others..
A search landed me at this page, but it wasn't quite what I was looking for. Posting here in case someone else looking for what I was lands at this page too.
There is two ways to do it if you only have a string value.
.NET way:
Same as #Canavar, but you can instantiate a new Uri Object
String URL = "http://localhost:1302/TESTERS/Default6.aspx";
System.Uri uri = new System.Uri(URL);
which means you can use the same methods, e.g.
string url = uri.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx
string host = uri.host
// localhost
Regex way:
Getting parts of a URL (Regex)
I guess its enough to return absolute path..
Path.GetFileName( Request.Url.AbsolutePath )
using System.IO;

Categories