rename url content - c#

when url= http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021 .
change content MainPP.aspx by idCompany
for example idCompany=142707090021 equal companyName microsoft
no how can when user enter url: http://www.iranfairco.com/microsoft this equal above url
how can http://www.iranfairco.com/MainPP.aspx?idCompany=142707090021====url:http://www.iranfairco.com/microsoft

You should use some url rewrite module (or write your own - it's not hard).
For example: IIS URL Rewrite, also look here.
Look at also this thourough explanation of how URL Rewriting in ASP.NET works.

Related

Rewriting forward slashes in a query parameter

In my asp.net core app (angular 4 front end) I accept a URL like this:
example.com/report;url=http%3A%2F%2Fexample2.com
I would like to create a rewrite rule that allowed people to enter the following url:
example.com/report;url=http://example2.com
I can't find out how to do this.
I tried:
var options = new RewriteOptions()
.AddRewrite(#"(.*);url=http:\/\/([^;]*)(.*)", "$1;url=http%3A%2F%2F$2$3", skipRemainingRules: false)
.AddRewrite(#"^report.*", "index.html", skipRemainingRules: true)
app.UseRewriter(options);
This didn't work but even if it did it wouldn't account for urls that have slashes after the domain, i.e. sub directories. Using a group matching pattern I think it's impossible to do that. It needs to be a find & replace type operation on matched group.
Other webservers have this as a configurable option to decode slashes. I can't find any reference to it in the asp.net core docs. Is this possible?
You're going to want to pass a parameter for the URL. There really is no way to get you what you want by allowing the user to enter a URL as a parameter in the address bar. It will always need to be encoded.
Instead of:
http://example.com/report;url=http%3A%2F%2Fexample2.com
use:
http://example.com/report?url=http%3A%2F%2Fexample2.com
Rather than having the user enter all of this into a browser address bar, I would instead create a user interface that allows a user to ask for a report and hit submit. The report would need a textbox for the URL and it will send a get request to your site after encoding the contents of the URL textbox into the 'url' parameter.
Using a URL re-write module is probably going against the grain here.
Unfortunately based on the code of the RewriteRule class, it is not possible. You should be able to create your own custom rewrite rule though which would implement IRule interface and URL encode part of your request path.
The source code of the RewriteRule can be found here
https://github.com/aspnet/BasicMiddleware/blob/dev/src/Microsoft.AspNetCore.Rewrite/Internal/RewriteRule.cs
And here is the UrlEncoder to encode the value of the 'url'
https://github.com/dotnet/corefx/blob/master/src/System.Text.Encodings.Web/src/System/Text/Encodings/Web/UrlEncoder.cs

Retrieve the Original (Client) Url Without the Default Document [duplicate]

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

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

Get the exact url the user typed into the browser

I would like to get the exact url that user typed into the browser. Of course I could always use something like Request.Url.ToString() but this does not give me what i want in the following situation:
http://www.mysite.com/rss
With the url above what Request.Url.ToString() would give me is:
http://www.mysite.com/rss/Default.aspx
Does anyone know how to accomplish this?
I have already tried:
Request.Url
Request.RawUrl
this.Request.ServerVariables["CACHE_URL"]
this.Request.ServerVariables["HTTP_URL"]
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "CACHE_URL")
((HttpWorkerRequest)((IServiceProvider)HttpContext.Current).GetService(typeof(HttpWorkerRequest))).GetServerVariable( "HTTP_URL")
Edit: You want the HttpWorkerRequest.GetServerVariable() with the key HTTP_URL or CACHE_URL. Note that the behavior differs between IIS 5 and IIS 6 (see documentation of the keys).
In order to be able to access all server variables (in case you get null), directly access the HttpWorkerRequest:
HttpWorkerRequest workerRequest =
(HttpWorkerRequest)((IServiceProvider)HttpContext.Current)
.GetService(typeof(HttpWorkerRequest));
Remember too that the "exact URL that the user entered" may never be available at the server. Each link in the chain from fingers to server can slightly modify the request.
For example if I type xheo.com into my browser window, IE will be convert to http://www.xheo.com automatically. Then when the request gets to IIS it says to the browser - you really want the default page at http://www.xheo.com/Default.aspx. So the browser responds by asking for the default page.
Same thing happens with HTTP 30x redirect requests. The server will likely only ever see the final request made by the browser.
Try using Request.Url.OriginalString
Might give you the thing you are looking for.
It is possible, you just need to combining a few of the values from the request object to rebuild the exact url entered:
Dim pageUrl As String = String.Format("{0}://{1}{2}",
Request.Url.Scheme,
Request.Url.Host,
Request.RawUrl)
Response.Write(pageUrl)
Entering the address http://yousite.com/?hello returns exactly:
http://yousite.com/?hello
Request.RawUrl
I think is the monkey you are after...
Easiest way to do this is used client-side programming to extract the exact url:
<script language="javascript" type="text/javascript">
document.write (document.location.href);
</script>

Categories

Resources