Read ID from URL and create a new one - c#

On Page_Load, I have to run code to check a url format. The url can be of the following formats:
http://www.xyzabc.com/DisplayProduct?ID=230 or
http://www.xyzabc.com/DisplayProduct?ID=230&blahblah or
http://www.xyzabc.com/S(yya4h4rf4gjh5eo4uazix2t055)X(1))/DisplayProduct?ID=230
Whenever the url has an ID, I want to create a url in the following format:
http://www.xyzabc.com/DisplayProduct?ID=<the id picked from the url>
Since the code will be run for every page (1500+) in the site, how can i write the best optimized code?

Make use of the URLRouting or make use of HTTPHandler/HTTPModule if possible............
here is link on msdn for this : URL Rewriting in ASP.NET

something like this:
int ID = 0;
int.TryParse(Request.QueryString["ID"], out ID);
if (ID > 0)
{
Response.Redirect(String.Format("http://www.xyzabc.com/DisplayProduct?ID={0}", ID));
}

you can do it by creating custom httpmodule to handle request and rewrite url
see this URL Rewriting in ASP.NET

You can use HttpModules for this, by using
context.BeginRequest += context_BeginRequest;
and in context_BeginRequest you do something like:
context.Response.Redirect(..)
This would be somewhat very "raw" solution, where you have multiple URL rewriting engines for ASP.NET, just check the Internet / SO for these....

Response.Redirect("http://www.xyzabc.com/DisplayProduct?ID=" + Request.QueryString["ID"].ToString().Trim());

Use URL Rewriting Libaray and configure it in web.config to avoid extra code.

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.

How to get current request url in Sharepoint 2013 in C#?

How to get current request url
I type in browser:
http://srv-1/sites/1001/Account Documents/Order
but in Page_Load in my controls I get
HttpContext.Current.Request.Url = http://srv-1/_layouts/15/start.aspx
and
Page.Request.RawUrl = Page.Request.RawUrl
I need to retrieve information: /Account Documents/Order
This happens because of Minimal Download Strategy feature. Your url is rewritten by SharePoint.
Easiest solution is to disable this feature, but you can also try to get url via SPUtility.OriginalServerRelativeRequestUrl property or refactor your code not use url, but current library or something else.
SharePoint does it’s own URL rewrites, if you would try that for example for the page
The solution is to use special property on [SPUtility class – SPUtility.OriginalServerRelativeRequestUrl][1]
http://blog.voyta.net/2012/07/09/how-to-get-original-request-url-in-sharepoint/
This property returns the original URL before it was rewritten, which is useful if you need to get the subweb from which an application page was loaded.
As this URL is server-relative, to get full url, you can use:
SPUtility.GetFullUrl(SPContext.Current.Site,
SPUtility.OriginalServerRelativeRequestUrl);
This can be useful if you need to redirect for example to the same URL with some additional parameters.
Thanks

How to short a URL

I have a URL like:
www.zzz.com/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf
I want to provide something short for ExternalDocuments/ExternalDocumentUpload.aspx. I don't want to shorten the whole url.
It sounds like what you want isn't "shortening" -- where a service like e.g. bit.ly is used to shorten the entire URL for use in Twitter or suchlike -- but "URL rewriting".
This takes a "friendly" path provided by the user -- to the right of the "/" -- and turns it into the URL you need for ASP.NET to find the page.
There's a few different ways to do this depending on precisely which flavour of ASP.NET and IIS you're using. ScottGu has a good roundup here:
http://weblogs.asp.net/scottgu/archive/2007/02/26/tip-trick-url-rewriting-with-asp-net.aspx
and for IIS7 I've used the one here:
http://www.iis.net/download/URLRewrite
You can set up url rewriting in global.asax file, on Application_BeginRequest event, that would run on every request, checking requested url and, if needed, redirecting it to desired url. You can make the checking like this:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.RawUrl== "/someShorturl/page.aspx")
{
HttpContext.Current.RewritePath("/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf");
}
}
So, if user goes to "www.zzz.com/someShorturl/page.aspx", he will get "www.zzz.com/ExternalDocuments/ExternalDocumentUpload.aspx?hjgbasdjfjsggfsdf" page, although url in the browser won't change.
If you'd like to change shortened url into long original url, you can call Response.Redirect instead the RewritePath method.
This example is for one speciffic url, but you can create more complex logic, of course.

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

Remove QueryString Variable in c#

I am very beginner With Programming...(unfortunately)
I want to remove Any added QueryString To Address after i get the variables. for example:
www.websiteName.com/page.aspx?a=344&b=233
i will get a and b and after that i want my address to look like this:
(www.websiteName.com) .
"root location".
any help...
thanks.
var queryString = Request.QueryString;
// Handle querystring, then redirect to root
Response.Redirect("~/");
Response.End();
You will have to reload the page. When changing the URL, you are making another request to the server.
I wrote a blog on retrieving the URL of an ASP.Net application. Simply add the page name after the result.
This blog describes how to manipulate the query string to redirect to the same page with different (or no) parameters.
Why not just use
Request.UserHostName

Categories