Is there a way to assign an external URL to a HyperLink without appending http:// or https:// (ie, the protocol)? - asp.net

I have a HyperLink defined like so:
<asp:HyperLink ID="hltest" runat="server"></asp:HyperLink>
In my code, I do this:
hltest.NavigateUrl = "www.google.com"
However, the actual link looks like this:
http://localhost:53305/www.google.com
I can append http:// to the URL, but this not the preferred method because this URL is maintainable by the user. If the user saves the URL as http://www.google.com then the URL will end up looking like http://http://www.google.com. I know that I can strip http:// from the URL and then add it back to ensure that it doesn't show up twice, but this is extra code/helper method that I would like to avoid writing.
Edit: This is the type of code I am trying to avoid having to write:
hltest.NavigateUrl = "http://" & "hTTp://www.google.com".ToLower().Replace("http://", String.Empty)
Update I know I specifically asked how to do this without appending the protocol to the URL, but it looks like there's just no other way to do it. The selected answer brought me to this solution:
Function GetExternalUrl(Url As String) As String
Return If(New Uri(Url, UriKind.RelativeOrAbsolute).IsAbsoluteUri, Url, "http://" & Url)
End Function
This is great because, if the user enters just www.google.com, it will append http:// to the URL. If the user provides the protocol (http, https, ftp, etc), it will preserve it.

Use the Uri class and handle it accordingly:
Uri uri = new Uri( userProvidedUri, UriKind.RelativeOrAbsolute );
if( !uri.IsAbsolute ) hltest.NavigateUrl = "http://" + userProvidedUri;
else hltest.NavigateUrl = userProvidedUri;

Related

DNN rewriting URL and adding Default.aspx? in Query-String

I have a Product list page on DNN.
On this module I have a function which is called when clicked. I am adding the name of the product and SKU in the URL as a Querystring. I noticed that DNN would rewrite ?Title= to /Title/ as well as &SKU= to /SKU/ when the SKU is normal without a forward slash. For example SKU/SR2018B
The URL below would work:
www.ourwebsite.com/Product-View/Title/staple-remover-black/sku/SR2018B
My main problem is when the SKU has a special character like a forward slash, for example: SS023/10. This will cause the URL to break. I am using an encoder for the SKU. Notice that ?Title did not change to /Title/ and now there is a Default.aspx? present in the URL below.
www.ourwebsite.com/Product-View?Title/staples-2313-1000pcs-100-pages/Default.aspx?sku=SS023%2f13
Here is my Code Behind when a person is redirected to the Detailed Page.
if (tabIdToRedirectTo == null) m_alerts.ShowModuleMessage(ModuleMessage.ModuleMessageType.RedError, $"An error occurred when attempting to Redirect to the '{settingKey}' Page!", ref plcMessages, true); else Response.Redirect(Globals.NavigateURL(tabIdToRedirectTo.TabID, "", "?Title="+ hiddendescription.Value + "&sku=" + HttpUtility.UrlEncode(hiddensku.Value), EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)));
I believe it's how you're calling the Globals.NavigateUrl function. The call takes a params of strings which are your query strings in the key=value format. I usually like to easily see what I am about to pass so I do something like the following:
var qsParams = new List<string>{
"Title=" + hiddendescription.Value, // "Title=staples-2313-1000pcs-100-pages"
"sku=" + HttpUtility.UrlEncode(hiddensku.Value), // "sku=SS023%2f13"
EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)
};
return Globals.NavigateURL(tabIdToRedirectTo.TabID, "", qsParams.ToArray());
Granted - I do not know what your EmbeddedModule.GenerateFullQueryStringForEmbedding does, but as long as it returns a key=value type output, it should be passed and processed well.

Check if string matches url

I've got a string url e.g. "http://localhost:3839/MyController/Statement1/myResult"
I need to do some logic on this i.e. if the url contains MyController/ and /myResult I need to redirect somewhere else.
Whats the easiest way to do this? I'm trying with regex but not sure how to do this.
You can do like below
string strURL=#"http://localhost:3839/MyController/Statement1/myResult";
if(strURL.contains("MyController") || strURL.contains("myResult")
{
//redirect logic here
}
What you could do is create a new Uri instance, which will do the parsing for you. You can create an Uri instance for you URL as follows:
var uri = new Uri("http://localhost:3839/MyController/Statement1/myResult");
You can then use the properties of the Uri instance to extract the different parts of the URI:
Console.WriteLine(uri.AbsolutePath); // outputs "/MyController/Statement1/myResult"
Console.WriteLine(uri.Scheme); // outputs "http"
Console.WriteLine(uri.Host); // outputs "localhost"
Console.WriteLine(uri.Port); // outputs "3839"

RouteCollection Querysting

I am trying to define MapPageRoute on the application global.asax but my problem is that I can not route the specific URL to a physical file with a query string.
For example I want to redirect http://mysite.com/Apple to http://mysite.com/product.aspx?id=95.
What I managed to achieve so far is if a user ask for ./Apple he will be redirected to ./product.aspx but I can not pass the query string.
Looking forward for your comments.
Try this:
if (Page.RouteData.Values["Apple"] != null)
{
int appleID = Convert.ToInt32(Page.RouteData.Values["Apple"]);
Response.Redirect("~/product.aspx?id=" + appleID.ToString(), true);
}

asp.net url minus pagename and querystring

I've been looking around the web for a simple and straight forward solution for the following problem but I cant seem to find anything that suits my needs.
I have an asp.net site with many subdirectories as follows.
http://mysite.com/dir1/subdir1/
http://mysite.com/dir1/subdir2/
http://mysite.com/dir2/
http://mysite.com/dir3/subdir1/
etc...
On each of my sites pages I need to extract the URL to the page minus the pagename and querystring.
So if the page name was http://mysite.com/dir1/subdir2/mypage.aspx?param=5&param2=9
I would need the following http://mysite.com/dir1/subdir2/ I cant find any properties of the httprequest object that make this URL format readily available.
Take a look at this. It should give you everything you need, especially Url.Segments.
This works as well:
System.IO.Path.GetDirectoryName(url).Replace(#"\","/");
You're right, such thing is not ready so you need to make it yourself. One recipe is:
public string GetSubFolderURL()
{
string url = "http";
if (string.Equals(Request.ServerVariables["HTTPS"], "ON", StringComparison.CurrentCultureIgnoreCase))
url += "s";
url += "://";
url += Request.ServerVariables["SERVER_NAME"];
int port;
if (Int32.TryParse(Request.ServerVariables["SERVER_PORT"], out port) && port != 80)
url += ":" + port;
url += Request.ServerVariables["SCRIPT_NAME"];
return url.Substring(0, url.LastIndexOf("/") + 1);
}

SEO: Duplicated URLs with and without dash "/" and ASP.NET MVC

after reading this article "Slash or not to slash" (link: http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html) on Google Webmaster Central Blog (the oficial one) I decided to test my ASP.NET MVC app.
For example:
http://domain.com/products and http://domain.com/products/ (with "/" in the end), return the code 200, which means: Google understands it as two different links and likely to be a "duplicated content". They suggest to choose the way you want... with or without dash and create a 301 permanent redirect to the preferred way.
So if I choose without dash, when I try to access http://domain.com/products/ it will return a 301 to the link without dash: http://domain.com/products.
The question is, how can I do that with ASP.NET MVC?
Thanks,
Gui
If your using IIS 7 you could use the URL Rewrite Extension ScottGu has a blog post about it here.
Alternatively if you want to do it in code you could inherit from PerRequestTask. Here some sample code the removes the www from an address - this is from Shrinkr:
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
You would just need to check for the url ending with a / in your code.
** Note this does use a 3rd party dll - System.Web.MVC.Extensibility namespace. **
It dosnt matter really for Google, but what does matter is if both urls'
http://domain.com/products and http://domain.com/products/ show the same page, you also need to watch with windows servers that links to your site like from external pages where the user has typed http://domain.com/PRODUCTS/ will aloso be seen as a diffrent page as the web is case sensitive.
There is away round this with the use of canonical url meta tag, it tell s google what the page name is really, so will avoid duplicate pages which ant really diuplicate
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
you need to check the URI in the INIT event and check the URI to see if it coming in with the slash, if it is, simply do a redirect and add the 301 header to the output response.

Resources