How to short a URL - c#

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.

Related

How to manipulate a url to access a parent directory

I have an asp.net web application that is being hosted on an internal network. In my testing environment of course it gets hosted out on localhost:01010/Views/page.aspx. now whenever I take it live the Url changes to server_name/folder 1/folder 2/views/page.aspx. what I am trying to do is get a new page to open up as server_name/folder 1/folder 2/Uploaded_Images/randomimage.png. Now I Can get the url, but as soon as I do a single ".Remove(url.lastindexof("/")+1)" it returns "server_name/folder 1/folder 2/Views". The I perform my second ".Remove(url.lastindexof("/")+1)"
and the it only returns "server_name/". I am ripping my hair out at this one and am hoping somewhere in the world a .net developer already has this built in. Appreciate all the help.
Also just to specify this is webforms and not mvc. also there is no ajax or page manipulation going on except for a response.write to open the new page.
You don't need the +1, this works:
var url = "server_name/folder 1/folder 2/views/page.aspx";
url = url.Remove(url.LastIndexOf("/"));
url = url.Remove(url.LastIndexOf("/"));
Or you could do it like this:
var parts = url.Split('/');
var newPath = string.Join("/", parts.Take(3));
I assume you are talking about URL's used as links to parts of your site and not physical paths on the file system.
In most cases, you should be able to use methods that construct paths on the fly. For example, in any of your .aspx files (or .aspx.cs files), you can use the ResolveUrl method, like this:
Some link
If there are any places where you need the full URL including the domain (like for email notifications or something like that) then what I have done is keep a static variable accessible to my whole application that gets set the first time Application_BeginRequest runs:
void Application_BeginRequest(object sender, EventArgs e) {
if (SiteRoot == null) {
SiteRoot = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
(VirtualPathUtility.ToAbsolute("~") == "/" ? "" : VirtualPathUtility.ToAbsolute("~"));
}
}
That will pull the full URL from the Request details (the URL that the user used to access your site), without any trailing slash.

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.

MVC 4 Lose Session Because Redirects From www.website.com to website.com

I just realize that session is lost when redirecting from www.website.com to website.com without www.
However I am quite lucky that I can set up the server so all redirection is start with www. In the future I do not want my application to be server dependent, I want to make it code dependent.
For example:
#Html.Hidden("PageManagerUrl", Url.Action("PageManager","Admin"))
produces /Admin/PageManager/, and I use location.href = url (when url is /Admin/PageManager/.
It is not 100% sure that I will lose my session at the first time of redirection, but when I tested it but redirecting back and forward, about the 3rd or 4th time, the session will be lost. After I set up the server setting to:
Preferred domain * www.website.com
Select the URL (either with or without the www. prefix) to which site visitors will be redirected via a SEO-safe HTTP 301 redirect.`
The session is never lost again. So I wonder, how to do the best redirection without losing my session? Please give me example how to do it from controllers and javascript / views.
Do you have any global.asax file ?
If yes, then please check whether it contains these two methods signature.
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}

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

ReportViewer "Missing URL parameter: Name"

In a web application I'm working on the ReportViewer keeps giving me a error "Missing URL parameter: Name". I have found the cause but not a solution.
The url that is causing the exception from the report viewer
Reserved.ReportViewerWebControl.axd?ReportSession=3bkunv2wte3wmnabkquyr1y0&ControlID=1e2b5870e07b46abac7fd32a9e0e4b9d&Culture=1033&UICulture=1033&ReportStack=1&OpType=ReportArea&Controller=ctl00_ASPxRoundPanel3_PageContent_Wizard1_ReportViewer1&PageNumber=1&ZoomMode=Percent&ZoomPct=100&ReloadDocMap=true&SearchStartPage=0&LinkTarget=_top
if you notice in the query string instead of "&name=" for some reason it becomes "&amp ;Name=".
I noticed on numinous google searches there seams to be a lot of people having the same problem but not one solution.
Sounds like something is mangling your URL somewhere. Do you by chance have a Bluecoat proxy in place? I saw something about Bluecoat mangling the URL.
If that's the case and you have control over the proxy, you might be able to get a tunnel punched through it for your reports. Otherwise, you might have to rewrite the URL on your end.
Check here for more information (last post in the thread has a possible workaround).
You can fix this globally by checking for the BlueCoat request header at the start of each request. This bit of code placed in global.asax.cs fixes the problem:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Fix incorrect URL encoding by buggy BlueCoat proxy servers:
if (!String.IsNullOrEmpty(Request.ServerVariables["HTTP_X_BLUECOAT_VIA"]))
{
string original = Request.QueryString.ToString();
if (original.Contains(Server.UrlEncode("amp;")))
{
HttpContext.Current.RewritePath(Request.Path + "?" + original.Replace(Server.UrlEncode("amp;"), "&"));
}
}
}
I'm not sure if any other proxy servers have the same issue, but if they do, this could be easily be adapted to check for the presence of & in the QueryString instead of checking for the BlueCoat header (or I guess, you could just check for the headers of any other affected products, which might be safer.

Categories