To make it simpler for a webapp to share files with another app on a different server, I'm using a base href tag in my master page. As many people have discovered, this breaks webform paths. I have a working Form Adaptor class but am not sure how to get the absolute path of the url. Currently, my program is hardcoded to use something akin to :
HttpContext Context = HttpContext.Current;
value = "http://localhost" + Context.Request.RawUrl;
It is worth noting that I'm currently testing on my local IIS server, so there's a strange tendency for a lot of things I've tried using in order what the absolute path do not include the domain name (my local IIS is not visible externally). Which means it isn't an absolute path and thus the base href will wreck it.
Is there a good way to handle this such that it will work locally without hardcoding but will also work properly when uploaded to a server? I'd prefer to avoid anything that involves doing something different on the server-side copy.
Yes, I realize I could use separate web.config files locally and on the server to get this information but this is ugly and violates DRY.
I have used this in the past:
// Gets the base url in the following format:
// "http(s)://domain(:port)/AppPath"
HttpContext.Current.Request.Url.Scheme
+ "://"
+ HttpContext.Current.Request.Url.Authority
+ HttpContext.Current.Request.ApplicationPath;
Old post but here is another slightly less verbose method
var baseUri = new Uri(HttpContext.Current.Request.Url, "/");
Using string interpolation:
string redirectUri = $"{this.Request.Url.Scheme}://{this.Request.Url.Authority}{this.Request.ApplicationPath}account/signedout";
Substitute 'this' for 'HttpContext' or 'HttpContext.Current' based on context.
I have used following and it worked for me both client and the server.
string surl = string.Format("{0}://{1}",
HttpContext.Current.Request.Url.Scheme,
HttpContext.Current.Request.Url.Authority);
Code :
string loginUrl = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/") + "Login/Login.aspx?UserName=" + LoggedinUser["UserName"] + "&Password=" + LoggedinUser["Password"];
Related
I want to get the current domain name in asp.net c#.
I am using this code.
string DomainName = HttpContext.Current.Request.Url.Host;
My URL is localhost:5858but it's returning only localhost.
Now, I am using my project in localhost. I want to get localhost:5858.
For another example, when I am using this domain
www.somedomainname.com
I want to get somedomainname.com
Please give me an idea how to get the current domain name.
Try getting the “left part” of the url, like this:
string domainName = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
This will give you either http://localhost:5858 or https://www.somedomainname.com whether you're on local or production. If you want to drop the www part, you should configure IIS to do so, but that's another topic.
Do note that the resulting URL will not have a trailing slash.
Using Request.Url.Host is appropriate - it's how you retrieve the value of the HTTP Host: header, which specifies which hostname (domain name) the UA (browser) wants, as the Resource-path part of the HTTP request does not include the hostname.
Note that localhost:5858 is not a domain name, it is an endpoint specifier, also known as an "authority", which includes the hostname and TCP port number. This is retrieved by accessing Request.Uri.Authority.
Furthermore, it is not valid to get somedomain.com from www.somedomain.com because a webserver could be configured to serve a different site for www.somedomain.com compared to somedomain.com, however if you are sure this is valid in your case then you'll need to manually parse the hostname, though using String.Split('.') works in a pinch.
Note that webserver (IIS) configuration is distinct from ASP.NET's configuration, and that ASP.NET is actually completely ignorant of the HTTP binding configuration of the websites and web-applications that it runs under. The fact that both IIS and ASP.NET share the same configuration files (web.config) is a red-herring.
Here is a screenshot of Request.RequestUri and all its properties for everyone's reference.
You can try the following code :
Request.Url.Host +
(Request.Url.IsDefaultPort ? "" : ":" + Request.Url.Port)
I use it like this in asp.net core 3.1
var url =Request.Scheme+"://"+ Request.Host.Value;
www.somedomain.com is the domain/host. The subdomain is an important part. www. is often used interchangeably with not having one, but that has to be set up as a rule (even if it's set by default) because they are not equivalent. Think of another subdomain, like mx.. That probably has a different target than www..
Given that, I'd advise not doing this sort of thing. That said, since you're asking I imagine you have a good reason.
Personally, I'd suggest special-casing www. for this.
string host = HttpContext.Current.Request.Url.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);;
if (host.StartsWith("www."))
return host.Substring(4);
else
return host;
Otherwise, if you're really 100% sure that you want to chop off any subdomain, you'll need something a tad more complicated.
string host = ...;
int lastDot = host.LastIndexOf('.');
int secondToLastDot = host.Substring(0, lastDot).LastIndexOf('.');
if (secondToLastDot > -1)
return host.Substring(secondToLastDot + 1);
else
return host;
Getting the port is just like other people have said.
HttpContext.Current.Request.Url.Host is returning the correct values. If you run it on www.somedomainname.com it will give you www.somedomainname.com. If you want to get the 5858 as well you need to use
HttpContext.Current.Request.Url.Port
the Request.ServerVariables object works for me. I don't know of any reason not to use it.
ServerVariables["SERVER_NAME"] and ServerVariables["HTTP_URL"] should get what you're looking for
You can try the following code to get fully qualified domain name:
Request.Url.Scheme + System.Uri.SchemeDelimiter + Request.Url.Host
Here is a quick easy way to just get the name of the url.
var urlHost = HttpContext.Current.Request.Url.Host;
var xUrlHost = urlHost.Split('.');
foreach(var thing in xUrlHost)
{
if(thing != "www" && thing != "com")
{
urlHost = thing;
}
}
To get base URL in MVC even with subdomain www.somedomain.com/subdomain:
var url = $"{Request.Url.GetLeftPart(UriPartial.Authority)}{Url.Content("~/")}";
string domainName = HttpContext.Request.Host.Value;
this line should solve it
Try this:
#Request.Url.GetLeftPart(UriPartial.Authority)
I have searched everywhere and I cannot find out how to pass my API key in with my request. I am setup to run from a specific IP address. I keep hitting my limit though. I think I am also hitting my time limits. I will introduce a sleep in my code. Otherwise, is there anything else I can check?? I am using the distance matrix with json output. I have turned on Google Maps API V3. I have a key and have a project. It seems like the service is still treating me like a free customer.
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&mode=driving&language=en-EN&sensor=false&units=imperial";
I have also tried two more approaches with my key and I get a denied request from both of them.
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&key=mykey&mode=driving&language=en-EN&sensor=false&units=imperial";
and
string url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=" +
origin + "&destinations=" + sDestination + "&key={mykey}&mode=driving&language=en-EN&sensor=false&units=imperial";
I was not sure if the curly braces were required or not. Both of the later lines of code result in request denials.
Looks to me like you just pass the key right in the URL, at least for the regular maps API. Take a look at the "Hello World" example in the documentation. It might work the same for the distance matrix. Have you tried it that way?
I have an s3 bucket called foo.example.com, which is all CNAMEd correctly.
I'm switching to the latest AWS .net SDK.
I wish to generate pre signed url like:
http://foo.example.com/myfile.txt?s3_params_here
Note the vanity cname there.
I have:
string bucketName = "foo.example.com";
AmazonS3Client s3Client = new AmazonS3Client("bar", "xxx",
new AmazonS3Config
{
ServiceURL = bucketName,
CommunicationProtocol = Protocol.HTTP
});
string key = "myfile.txt";
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
string url = s3Client.GetPreSignedURL(request);
the url I get is something like:
http://foo.example.com.foo.example.com/myfile.txt?AWSAccessKeyId=bar&Expires=1331069777&Signature=234KoUUvfE1nCcs2vLj9RQUhqF8%3D
Which is clearly wrong.
I've tried a buch of different variations with ServiceURL, bucketname, etc, but nothing seems to work.
I can't find any good documentation - what is the correct way to do this?
Thanks.
Update [workaround]
I've meanwhile resolved the contradicting test results of mine, which stem from respectively unsystematic testing and URL manipulations. The following workaround does the trick for me (i.e. tested and reproducible), simply starting from your solution:
string bucketName = "foo.example.com";
// [...]
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithBucketName(bucketName)
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(32))
.WithProtocol(Protocol.HTTP);
Now this yields the erroneous URL with a duplicate domain name, i.e. http://foo.example.com.foo.example.com/myfile.txt?[...]
The duplicate can simply be removed though, e.g.:
string url = s3Client.GetPreSignedURL(request);
// KLUDGE: remove duplicate domain name.
url = url.Replace(bucketName + "." + bucketName, bucketName);
This yields a proper working pre-signed URL for me (i.e. http://foo.example.com/myfile.txt?[...]) by working around the encountered limitation regarding the desired approach outlined below.
Justification
Manipulating the generated URL like so seems odd, but this not having an effect on the query string authentication is in line with how these signatures are created, see Query String Request Authentication Alternative, where you'll find the pseudo-grammar that illustrates the query string request authentication method:
StringToSign = HTTP-VERB + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Expires + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
That is, the domain name isn't used for the signature creation at all, rather only information regarding the resource itself; section Example Query String Request Authentication right below the referenced pseudo-grammar fragment illustrates this with an actual resource.
Assessment
I don't know whether there is still a misunderstanding on our part or whether this might just be a bug in the AWS SDK for .NET, see e.g. Why is my S3 pre-signed request invalid when I set a response header override that contains a “+”? for a related bug resolved via a similar workaround as well, which has meanwhile been fixed though; accordingly, this should likely be escalated to the AWS forums and/or support channels to get an appropriate answer or solution.
Good luck!
Desired answer [dysfunctional]
The S3 CNAME handling implies the bucket name already, so all you need to do is removing your bucket name from GetPreSignedUrlRequest, i.e. it should look like so:
GetPreSignedUrlRequest request = new GetPreSignedUrlRequest()
.WithKey(key)
.WithExpires(DateTime.Now.AddMinutes(5))
.WithProtocol(Protocol.HTTP);
I've tested this with a bucket of mine and it works as expected like so.
the presignedURL returns an URL object after signing the request. I have used the same and >dont have real issues, but there are some things to consider:
Ensure the object URL you are considering does not have a '//' it could easily happen if >you start the storage path starts with a "/", you would have stored the object in a path some >thing like https:///x/y/z/abc.png the key for such a resource is x/y/z/abc.png >and not /x/y/z/abc.png
If the above is ensured, then from the URL object that is returned get the query parameters >from the URL object url.getQuery() will return the query parameters which contains the >signature information, just suffix this with your original awsURL and things should work with >out any encoding issues.
Hope this helps..
Essentially you need to use url.getQuery on the returned url object rather than simply affixing it to the end of your bucket.
https://forums.aws.amazon.com/thread.jspa?threadID=70521
I'm following a tutorial on this link http://www.codeproject.com/KB/aspnet/ASPNETService.aspx
Now I'm stuck at these codes
private const string DummyPageUrl =
"http://localhost/TestCacheTimeout/WebForm1.aspx";
private void HitPage()
{
WebClient client = new WebClient();
client.DownloadData(DummyPageUrl);
}
My local application address has a port number after "localhost", so how can I get the full path (can it be done in Application_Start method)? I want it to be very generic so that it can work in any cases.
Thanks a lot!
UPDATE
I tried this in the Application_Start and it runs fine, but return error right away when published to IIS7
String path = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/");
If it is calling back to the same server, perhaps use the Request object:
var url = new Uri(Request.Url, "/TestCacheTimeout/WebForm1.aspx").AbsoluteUri;
Otherwise, store the other server's details in a config file or the database, and just give it the right value.
But a better question would be: why would you talk via http to yourself? Why not just call a class method? Personally I'd be using an external scheduled job to do this.
You need an answer that works when you roll out to a different environment that maybe has a virtual application folder.
// r is Request.Url
var url = new Uri(r, System.Web.VirtualPathUtility.ToAbsolute("~/Folder/folder/page.aspx")).AbsoluteUri;
This will work in all cases and no nasty surprises when you deploy.
I suspect you're using the ASP.NET development server that's built-in to Visual Studio, which has a tendency to change port numbers by default. If that's the case, then you might try simply configuring the development server to always use the same port, as described here. Then just add the port number to your URL, like so:
private const string DummyPageUrl =
"http://localhost:42001/TestCacheTimeout/WebForm1.aspx";
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.