I have the following code:
if (Request.Url.AbsolutePath == "/Guidance.aspx")
{
if (Request.IsSecureConnection)
{
Reponse.Redirect("http://www.example.com/Guidance.aspx");
}
return;
}
The thing is that Guidance can have a querystring with it. I like to then Redirect to the same page name and append the querystring. Haven't found a way to do this.
if (Request.Url.AbsolutePath == "/Guidance.aspx?id='vid09'")
{
if (Request.IsSecureConnection)
{
Reponse.Redirect("http://www.example.com/Guidance.aspx?id='vid09'");
}
return;
}
How can I simplify the code above to do it with any querystring that comes its way.
Use UriBuilder and replace parts you need. Something like:
var builder = new UriBuilder(Request.Url);
builder.Scheme = "http";
Reponse.Redirect(builder.ToString);
string myUrl = Request.RawUrl.toString();
if (myUrl.Contains("/Guidance.aspx")
{
if (Request.IsSecureConnection)
{
var queryString = myUrl.Substring(myUrl.IndexOf("?"));
Reponse.Redirect("http://www.example.com/Guidance.aspx" + queryString);
}
return;
}
Don't get fancy, the URI is already parsed for you (don't do it yourself with unreliable regular expressions). The Url property you're using is a System.Uri object. You may simply compare the scheme, host, and any HTTP segment you may need, then construct your redirection URI by adding only the query string component from the original URI. All you need is in the Uri class.
Related
I'm coding a simple URL shortener.
Everything is working, except the redirection.
Here is the code that tries to redirect:
public async Task<ActionResult> Click(string segment)
{
string referer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
Stat stat = await this._urlManager.Click(segment, referer, Request.UserHostAddress);
return this.RedirectPermanent(stat.ShortUrl.LongUrl);
}
When I input a link that is shortened, like this http://localhost:41343/5d8a2a, it redirects me to http://localhost:41343/www.google.com.br instead of www.google.com.br.
EDIT
After checking the answer, it works. Here is the final snippet of code.
if (!stat.ShortUrl.LongUrl.StartsWith("http://") && !stat.ShortUrl.LongUrl.StartsWith("https://"))
return this.RedirectPermanent("http://" + stat.ShortUrl.LongUrl);
else
return this.RedirectPermanent(stat.ShortUrl.LongUrl);
Thanks!
Instead of RedirectPermanent() try using Redirect() like below. The specified URL has to be a absolute URL else it will try to redirect to within your application.
You can check for existence of http:// and add it accordingly
if(!stat.ShortUrl.LongUrl.Contains("http://"))
return Redirect("http://" + stat.ShortUrl.LongUrl);
(OR)
Use StartsWith() string function
if(!stat.ShortUrl.LongUrl.StartsWith()("http://"))
return Redirect("http://" + stat.ShortUrl.LongUrl);
I have a string like
<Scheme>:\\<domain>\<domainuser>:<EncryptedPassword>#servername\
I want to be able to create Uniform resource identifier (URI) and easy access the parts of the URI. For most part using C# Uri class works great. But I get invalid URI exceptions when user is provided as "domainname\domainuser".
How best to handle this in C#.
You must PercentEncode(/EscapeDataString) such strings.
Like in question above username "xyz_domain\abc_user" must be encoded to "xyz_domain%5Cabc_user" to before creating URI object.
Later after extracting you can do PercentDecode(/UnescapeDataString) of the string using UnescapeDataString method from Uri Class.You can use UnescapeDataString Method from C# Uri Class
Here is the code
public static string GetUsername(this Uri uri)
{
if (uri == null || string.IsNullOrWhiteSpace(uri.UserInfo))
return string.Empty;
var items = uri.UserInfo.Split(new[] { ':' });
//Replace precent encoding in the username.
var result = Uri.UnescapeDataString(items[0]);
return result.Length > 0 ? result : string.Empty;
}
Similar scheme can be applied to any part of the uri string. Just remember to UnescapeDataString the EscapeDataStrings.
I asked a question to get URL as action input here. Now I have a new problem. The passed URL to action changes from http://example.com to http:/example.com.
I want to know why and how can I resolve the problem.
P.S: I added this code to resolve but I think there may be another problems in future! the code is:
if ((url.Contains(":/")) && !(url.Contains("://")))
{
url = url.Replace(":/", "://");
}
The browser (or server) is replacing a double slash (illegal) with a single one.
Try it,
http://stackoverflow.com/questions/11853025//input-url-like-http-site-com-changes-to-http-site-com-in-action-input
(in Chrome) goes to:
http://stackoverflow.com/questions/11853025/input-url-like-http-site-com-changes-to-http-site-com-in-action-input
If I were you, I would remove the http:// from your path and add it later.
http://localhost:1619/Utility/PR/example.com/
Then, url = "http://" + url;
If you might get secure urls, add that to the route /http/example.com or /https/example.com
use regex:
string src = #"http://example.com";
string result = Regex.Replace(src, #"(?<=https?:/)/", "");
if you need to revert:
string src = #"http:/example.com";
string result = Regex.Replace(src, #"(?<=https?:)/(?=[^/])", #"//");
i have a set of routes defined in System.Web.Routing and in need to get the actual url's with the .aspx extension. i've tried this code but i'm doing something wrong here:
var path = RouteTable.Routes.GetVirtualPath(null, item.Link, null);
var link = path.Route.GetVirtualPath(null, null);
if (link.VirtualPath.ToLower().Contains("~/displaycmspage.aspx?pagename="))
{
//do work on url here
}
any idea on how i can do this? The item.link is a custom object where i have the route.
ok, so i found the answer :
var path = RouteTable.Routes[item.Link];
Route ruta = path as Route;
var link = ruta.RouteHandler as PageRouteHandler;
if (link.VirtualPath.ToString().ToLower().Contains("~/displaycmspage.aspx?pagename="))
{
//do work on url here
}
Is there a better/more accurate/stricter method/way to find out if a URL is properly formatted?
Using:
bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Doesn't catch everything. If I type htttp://www.google.com and run that filter, it passes. Then I get a NotSupportedExceptionlater when calling WebRequest.Create.
This bad url will also make it past the following code (which is the only other filter I could find):
Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
url = nUrl.ToString();
}
The reason Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute) returns true is because it is in a form that could be a valid Uri. URI and URL are not the same.
See: What's the difference between a URI and a URL?
In your case, I would check that new Uri("htttp://www.google.com").Scheme was equal to http or https.
Technically, htttp://www.google.com is a properly formatted URL, according the URL specification. The NotSupportedException was thrown because htttp isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten a UriFormatException. If you just care about HTTP(S) URLs, then just check the scheme as well.
#Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.
public static bool Url(string p_strValue)
{
if (Uri.IsWellFormedUriString(p_strValue, UriKind.RelativeOrAbsolute))
{
Uri l_strUri = new Uri(p_strValue);
return (l_strUri.Scheme == Uri.UriSchemeHttp || l_strUri.Scheme == Uri.UriSchemeHttps);
}
else
{
return false;
}
}
This Code works fine for me to check a Textbox have valid URL format
if((!string.IsNullOrEmpty(TXBProductionURL.Text)) && (Uri.IsWellFormedUriString(TXBProductionURL.Text, UriKind.Absolute)))
{
// assign as valid URL
isValidProductionURL = true;
}