Querystring as part of url - c#

I have a url with querystring http://www.sample.com?q=asdasdsdasd . Will it be possible to modify the querystring so that I could replace it with /myaccount i.e at the end the url will look like http://www.sample.com/myaccount.

string destUrl = string.Format("{0}://{1}{2}/",Request.Url.Scheme,Request.Url.Authority,Request.Url.AbsolutePath);
if (destUrl.EndsWith("/"))
destUrl = destUrl.TrimEnd(new char[] { '/' });
if (!string.IsNullOrEmpty(Request.QueryString["paramName"])) {
destUrl = string.Format("{0}?paramName={1}", destUrl, "paramValueHere");
Response.Redirect(destUrl);

Check out url rewriting. You may not be able to achieve the /myaccount direct, but you can tidy up your urls, make them more readable and meaningful for SEO.
You will be able to use to allow your url to look similar to the following :
www.sample.com/account/asdaasdasd
If you lose the query string all together you won't be able to access it at all. Unless you implemented some form of interim code that will get the query string, store it in a session and then redirect to your /myaccount url and get it back there.

I think you are referring to URL Rewriting.
This is quite a commonly used blog post regarding URL rewriting:
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
Or if you have IIS7, its now been made easier:
http://www.iis.net/download/urlrewrite
In terms of changing ?q=asdasdsdasd to /myaccount though, I don't understand. The first URL seems like a typical search query, and the second is a URL which would probably use cookies etc to pick up the variables (as its for a user account?).
But URL Rewriting can be used so that if you have a user profile with a URL like:
www.sample.com?userprofile.aspx?user=johnsmith
This can be rewritten, using the johnsmith part as a variable like:
www.sample.com/user/johnsmith

With simple string manipulation you could do it as:
string urlWithQuerystring = "http://www.sample.com?q=asdasdsdasd";
int queryStringPos = urlWithQuerystring.IndexOf("?");
string newUrl = String.Format("{0}/myaccount/", urlWithQuerystring.Substring(0, queryStringPos));

Use the this Code in your Global.asax:
void Application_BeginRequest(object sender, EventArgs e)
{
string[] parts = Request.RawUrl.Split(new char[]{'/'});
if(Part[1] == "myaccount"))
Context.RewritePath("http://www.sample.com?q=" + Part[2]);
}
and then use this address
http://www.sample.com/myaccount/asdasdasd

Related

How to get current domain name in ASP.NET

I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;
My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com
I want to get somedomainname.com
Please give me an idea how to get the current domain name.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.
Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.
You can try the following code :
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Getting the port is just like other people have said.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for
You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Here is a quick easy way to just get the name of the url.
var urlHost = HttpContext.Current.Request.Url.Host;
var xUrlHost = urlHost.Split('.');
foreach(var thing in xUrlHost)
{
if(thing != "www" && thing != "com")
{
urlHost = thing;
}
}
To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
string domainName = HttpContext.Request.Host.Value;
this line should solve it
Try this:
#Request.Url.GetLeftPart(UriPartial.Authority)

Get value from Encoded Url

I am trying to get a value from a Encoded URL in C#. So for example, I am trying to get "customerID" from:
http://<DOMAIN>/default.aspx%3FcustomerID%3D12345%26reference%3D2222
I tried the following:
string customerID = HttpUtility.UrlDecode(Request.QueryString["customerID"]);
But it comes back NULL. What is the proper way to get this value??
Thanks
Jay
string str = " http://DOMAIN/default.aspx%3FcustomerID%3D12345%26reference%3D2222";
var url = HttpUtility.UrlDecode(str);
var parameters = HttpUtility.ParseQueryString(new Uri(url).Query);
var id = parameters["customerID"];
your application should be encoding the ? and = signs. The Request variables are setup by iis usually before the information is handed off to the application handling the request. You need to send the should encode values but not the entire url. If your url looked like,
?customerID=1234 I imagine it would work, the problem is not with your code but with how the url is being constructed.

Converting a web address to a valid href value

Firstly, this seems like something that should have been asked before, but I cannot find anything that answers my question.
A basic overview of my task is to render an anchor link on a web page which is based on a user defined web address. As the address is user defined this could be in any format, for example:
http://www.example.com
https://www.example.com
www.example.com
example.com
What I need to do with this value is to set it as the href property of an anchor tag. Now, the problem is that (in Chrome at least) only the first two examples will work due to the fact they are recognised as absolute URL paths. The last two examples will redirect to the same domain (i.e. treated as relative paths)
So the ultimate question is: What is the best way to format these values to ensure a consistent absolute path is used? I could check for http/https and add it if missing, but I was hoping there might be an out of the box .Net class that would be more reliable.
In addition, as this is a user defined value, it could be complete junk anyway so a function to validate the URL would be a nice bonus too.
We ran into this problem a few months back, and needed a consistent way of ensuring the URLs were absolute. We also wanted a way of removing http(s):// for displaying the URL on the web page.
I came up with this function:
public static string FormatUrl(string Url, bool IncludeHttp = null)
{
Url = Url.ToLower();
switch (IncludeHttp) {
case true:
if (!(Url.StartsWith("http://") || Url.StartsWith("https://")))
Url = "http://" + Url;
break;
case false:
if (Url.StartsWith("http://"))
Url = Url.Remove(0, "http://".Length);
if (Url.StartsWith("https://"))
Url = Url.Remove(0, "https://".Length);
break;
}
return Url;
}
I know you're after an "out of the box" library, but this may be of some help.
I think the problem with an "out of the box" solution would be that the function won't know whether the URL should be http:// or https://. With my function I've made an assumption that its going to be http://, but for some URLs you need https://. If Microsoft were to build something like this into the framework, it would be buggy from the start.
You can try using this overload of the Uri class:
Uri Constructor (String)
This constructor creates a Uri instance from a URI string. It parses the URI, puts it in canonical format, and makes any required escape encodings.
This constructor does not ensure that the Uri refers to an accessible resource.
This constructor assumes that the string parameter references an absolute URI and is equivalent to calling the Uri constructor with UriKind set to Absolute. If the string parameter passed to the constructor is a relative URI, this constructor will throw a UriFormatException.
This will try to construct a canonical Uri from the user input. And you have lots of properties to check and extract the URL parts that you need.

Truncating Query String & Returning Clean URL C# ASP.net

I would like to take the original URL, truncate the query string parameters, and return a cleaned up version of the URL. I would like it to occur across the whole application, so performing through the global.asax would be ideal. Also, I think a 301 redirect would be in order as well.
ie.
in: www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media
out: www.website.com/default.aspx
What would be the best way to achieve this?
System.Uri is your friend here. This has many helpful utilities on it, but the one you want is GetLeftPart:
string url = "http://www.website.com/default.aspx?utm_source=twitter&utm_medium=social-media";
Uri uri = new Uri(url);
Console.WriteLine(uri.GetLeftPart(UriPartial.Path));
This gives the output: http://www.website.com/default.aspx
[The Uri class does require the protocol, http://, to be specified]
GetLeftPart basicallys says "get the left part of the uri up to and including the part I specify". This can be Scheme (just the http:// bit), Authority (the www.website.com part), Path (the /default.aspx) or Query (the querystring).
Assuming you are on an aspx web page, you can then use Response.Redirect(newUrl) to redirect the caller.
Here is a simple trick
Dim uri = New Uri(Request.Url.AbsoluteUri)
dim reqURL = uri.GetLeftPart(UriPartial.Path)
Here is a quick way of getting the root path sans the full path and query.
string path = Request.Url.AbsoluteUri.Replace(Request.Url.PathAndQuery,"");
This may look a little better.
string rawUrl = String.Concat(this.GetApplicationUrl(), Request.RawUrl);
if (rawUrl.Contains("/post/"))
{
bool hasQueryStrings = Request.QueryString.Keys.Count > 1;
if (hasQueryStrings)
{
Uri uri = new Uri(rawUrl);
rawUrl = uri.GetLeftPart(UriPartial.Path);
HtmlLink canonical = new HtmlLink();
canonical.Href = rawUrl;
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);
}
}
Followed by a function to properly fetch the application URL.
Works perfectly.
I'm guessing that you want to do this because you want your users to see pretty looking URLs. The only way to get the client to "change" the URL in its address bar is to send it to a new location - i.e. you need to redirect them.
Are the query string parameters going to affect the output of your page? If so, you'll have to look at how to maintain state between requests (session variables, cookies, etc.) because your query string parameters will be lost as soon as you redirect to a page without them.
There are a few ways you can do this globally (in order of preference):
If you have direct control over your server environment then a configurable server module like ISAPI_ReWrite or IIS 7.0 URL Rewrite Module is a great approach.
A custom IHttpModule is a nice, reusable roll-your-own approach.
You can also do this in the global.asax as you suggest
You should only use the 301 response code if the resource has indeed moved permanently. Again, this depends on whether your application needs to use the query string parameters. If you use a permanent redirect a browser (that respects the 301 response code) will skip loading a URL like .../default.aspx?utm_source=twitter&utm_medium=social-media and load .../default.aspx - you'll never even know about the query string parameters.
Finally, you can use POST method requests. This gives you clean URLs and lets you pass parameters in, but will only work with <form> elements or requests you create using JavaScript.
Take a look at the UriBuilder class. You can create one with a url string, and the object will then parse this url and let you access just the elements you desire.
After completing whatever processing you need to do on the query string, just split the url on the question mark:
Dim _CleanUrl as String = Request.Url.AbsoluteUri.Split("?")(0)
Response.Redirect(_CleanUrl)
Granted, my solution is in VB.NET, but I'd imagine that it could be ported over pretty easily. And since we are only looking for the first element of the split, it even "fails" gracefully when there is no querystring.

Redirecting URL's

How can I redirect www.mysite.com/picture/12345 to www.mysite.com/picture/some-picture-title/12345? Right now, "/picture/12345" is rewritten on picture.aspx?picid=12345 and same for second form of url (picture/picture-title/12323 to picture.aspx?picid12323) I can't just rewrite first form of url to second because i have to fetch picture title from database.
On the first hand, problem looks very easy but having in mind time to parse every request, what would be the right thing to do with it?
Not knowing what is the ASP.NET technology (Webforms or MVC) I will assume it's WebForms.
You can have a look at URL Redirecting and build you own rules. And you do this one time only to apply to all of the links that look like you want.
Scott Guthrie has a very nice post about it.
If what you want is to when it comes to that address redirect to a new one, it's quite easy as well.
First of all let's reuse the code, so you will redirect first to a commum page called, for example, redirectme.aspx
in that page you get the REFERER address using the ServerVariables or passing the Url in a QueryString, it's your chooise and then you can attach the title name, like:
private void Redirect()
{
// get url: www.mysite.com/picture/12345
string refererUrl = Request.ServerVariables["HTTP_REFERER"]; // using the ServerVariables or Request.UrlReferrer.AbsolutePath;
//string refererUrl = Request.QueryString["url"]; // if you are redirecting as Response.Redirect("redirectme.aspx?" + Request.Url.Query);
// split the URL by '/'
string[] url = refererUrl.Split('/');
// get the postID
string topicID = url[url.Length-1];
// get the title from the post
string postTitle = GetPostTitle(topicID);
// redirect to: www.mysite.com/picture/some-picture-title/12345
Response.Redirect(
String.Format("{0}/{1}/{2}",
refererUrl.Substring(0, refererUrl.Length - topicID.Length),
postTitle,
topicID));
}
to save time on the server do this on the first Page event
protected void Page_PreInit(object sender, EventArgs e)
{
Redirect();
}
If you're running IIS7 then (for both webforms and MVC) the URL rewriting module (http://learn.iis.net/page.aspx/460/using-url-rewrite-module/) is worth looking at.
Supports pattern matching and regular expressions for redirects, state whether they're temporary or permanent, plus they're all managable through the console. Why code when you don't have to?
I'm presuming you need a common pattern here and not just a once off solution. i.e. you'll need it to work for 12345 & 12346 & whatever other IDs as well. You're probably looking for URLRedirection and applying a Regular Expression to identify a source URI that will redirect to your Target URI

Categories

Resources