Request.ServerVariables["SERVER_NAME"] is always localhost - asp.net

I'm developing an ASP.NET 3.5 application with Visual Studio 2008.
My default page has some redirection code in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string sname = Request.ServerVariables["SERVER_NAME"].ToLower();
if (sname.ToLower().Contains("intranet"))
{
Response.Redirect("/intranet/Default.aspx");
}
else if ((sname.ToLower().Contains("extranet")))
{
Response.Redirect("/extranet/Default.aspx");
}
else {
Response.Redirect("/web/Default.aspx");
}
}
I've modified my hosts file so that intranet and extranet redirect to my local machine.
127.0.0.1 intranet
127.0.0.1 extranet
I then type the URL http://extranet in my browser.
However, the problem is that the server variable value returned from Request.ServerVariables["SERVER_NAME"] is always "localhost" and not "extranet"
Any help on how to get the right value?
Many thanks

Request.ServerVariables["HTTP_HOST"] gets the value I was looking for :)

Youre right
You want to retrieve the full address of the website that the request came to. Do not use "SERVER_NAME", use "HTTP_HOST".
Read here,
http://www.requestservervariables.com/get-address-for-website

Server_Name returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs
Why don't you use Request.URL?

Your host files only redirect the requests to a specific IP address - you cannot change the requesting machines name by editing them.

Related

subdomain url redirects to the main url

I developed a website in asp.net and hosted on windows server which does not provide me the wild card entry for the subdomain name. How can I write my url as e.g
http://subdomainName.DomainName.org?
I want to redirect the url with a subdomain to the main domain; so url "subdomainName.DomainName.org" should redirect to "DomainName.org", where my subdomain name is not fixed. The subdomain will be assigned to each user.
How can I achieve this?
The subdomain is part of the DNS server, and work together with the IIS setup.
So, you can NOT change the DNS setup from asp.net, neither the IIS setup. When a provider gives your the access to add extra sub-domains, what is actually do is that create new entries on the DNS entry, and then add map that to the IIS, so that sub-domains to look at your site. If your provider did not have give you a tool to add sub-domains, nether you can edit the DNS entries, then you can NOT add them from asp.net.
If you can add sub-domains then you can manipulate what you going to server and show on global.asax at Application_BeginRequest using the redirect or the Rewrite the path. For example:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var SubDomain = GetSubDomain(HttpContext.Current.Request.Url.Host);
if(!String.IsNullOrEmpty(SubDomain) && SubDomain != "www")
{
Response.Redirect("www.yourdomain.com", true);
return;
}
}
// from : http://madskristensen.net/post/Retrieve-the-subdomain-from-a-URL-in-C.aspx
private static string GetSubDomain(Uri url)
{
string host = url.Host;
if (host.Split('.').Length > 1)
{
int index = host.IndexOf(".");
return host.Substring(0, index);
}
return null;
}
Similar posts:
How to remap all the request to a specific domain to subdirectory in ASP.NET
Redirect Web Page Requests to a Default Sub Folder
How to refer to main domain without hard-coding its name?
Retrieve the subdomain from a URL in C#

getting https to work locally in asp.net MVC4 application

I followed this tutorial exactly:
http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx
But when I am running locally and try to navigate from a non-https page (like home/index) to and a page I decorated with [RequireHttps] I get the generic "SSL connection error" message.
I hate posting such a generic question, but can you think of anything I have missed? It is a large asp.net mvc4 application, I enabled ssl in the project, it shows the ssl url. Navigating to the ssl url manually does not work either.
HALP!
NOTE: Using IIS Express with visual studio 2012
Per the comment, the error I am getting is Cannot Establish SSL connection.
You shouldn't be using Https when testing locally. I've created my own Https Filter where it will ignore all the local traffic in the localhost and only works either on staging and live environment. You can modify the code to suit you need.
public class RequireSSLAttribute : FilterAttribute, IAuthorizationFilter {
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if(filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if(!filterContext.HttpContext.Request.IsSecureConnection) {
HandleNonHttpsRequest(filterContext);
}
}
protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) {
if(filterContext.HttpContext.Request.Url.Host.Contains("localhost")) return;
if(!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException("The requested resource can only be accessed via SSL");
}
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
//ignore if the request is from a child action
if(!filterContext.IsChildAction) {
filterContext.Result = new RedirectResult(url);
}
}
}
And this is how you use it...
[RequireSSL(Order=1), Authorize(Order=2)]
public PartialViewResult AccountHeader() {
blah...blah...
}
I know it's already answered, but I thought I'd point out the cause of the original error, which the other answers omit.
When you enable SSL on IIS Express, your site is hosted on 2 ports, 1 for http and another for https. When you debug in Visual Studio, the port is usually specified explicitly. The links on your site probably don't specify port numbers, so when you link from a plain http page to a https one, the port number won't change, and you'll request a https page on the plain http port. This is why you get the SSL connection error.
On a real server the port numbers should be implicit, so the problem shouldn't come up, but you'll need to make sure you're using the right port when debugging locally.
You need to add ssl certificate to your site instance in IIS.
To create certifiacte and add it to IIS7 try this tutorial: http://technet.microsoft.com/en-us/library/cc753127(v=ws.10).aspx
After creation you'll be able to add it to your website. Open in IIS 'your website' -> Bindings -> Add and add new host header. Select https, port 443 and select created sertificate.

HTTP to HTTPS redirection in asp.net not working

We have a simple requirement to use https for certain specific pages in a asp.net 4.0 web application. For checking our implementation, we deployed a simple asp.net 4.0 app to IIS 7. The app has been coded to redirect the default.aspx page to securepage.aspx over https based on a web.config flag.
protected void Page_Load(object sender, EventArgs e)
{
Uri requestUri = Page.Request.Url;
UriBuilder builder = new UriBuilder("https", requestUri.Host, requestUri.Port, "SecurePage.aspx");
string secureUrl = builder.Uri.ToString();
if (bool.Parse(ConfigurationManager.AppSettings["UseSecure"]))
{
Response.Redirect(secureUrl, true);
}
else
{
Response.Write(secureUrl);
}
}
But after we deploy this app on IIS 7 and load the default.aspx page, it shows "Internet Explorer cannot display the webpage". But if we turn the config flag off, it displays the page properly. The app has http binding on port 82 and https on port 444.
Can anybody point me in where we are going wrong.
When you type in front https then the browser is go on port 443 and not on 444, so to movit on your custom port you need to type it as.
UriBuilder builder = new UriBuilder("http", requestUri.Host, 444, "SecurePage.aspx");
You are using the current request's port via requestUri.Port, which returns 80. You should hard-code the 444 instead:
UriBuilder builder = new UriBuilder("https", requestUri.Host, 444, "SecurePage.aspx");
Or use a configurable variable if the port changes.

Difference between http and https technique

Does it need Certificate/License/Registration before launching the website using https?
I want to use the mentioned code in Global.asax file.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+ HttpContext.Current.Request.RawUrl);
}
First of all, I think you will never reach it, as it will loop in the Application_BeginRequest over and over as you are redirecting all requests...
Maybe what you're after is redirecting if the request comes from a non secure connection (http), no?
for that, see if the request comes from such connection like:
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (!HttpContext.Current.Request.IsSecureConnection)
Response.Redirect(HttpContext.Current.Request.Url.AbsoluteUri.Replace("http://", "https://"));
}
Secondly, the HTTPS protocol needs to be up and running or you will get a ERR_SSL_PROTOCOL_ERROR error thrown.
In Visual Studio, you can easily enable https in the project properties
and you will get the untruest warning
As Visual Studio generated (on installation) a default self signed certificated.
In production environment you will need to:
if it's an intranet application, just use the self-signed certificate
on a internet application, you do need to buy an SSL certificates, now-days they re cheaper and cheaper...
From your comments I have some question myself now...
Do you understand what HTTPS does to the connection between client computer and server?
Do you really need a secure connection between the two?
What kind of data are you trying to secure?
When you want to use secure HTTP (using the HTTPS protocol) you say that the traffic between the browser and server is encrypted.
This means you need a certificate on the server so that the browser and server can decide on how to encrypt the traffic.
This has nothing to do with redirects and everything to do with your server setup.

How to Create Dynamic Sub-domain with ASP.NET?

How can I create a subdomain in an asp.net C# application? I am working with an asp.net portal.
I have my site which redirects all *.domain.com calls to domain.com. What I want to acheive is that first when the user enters a dynamic subdomain name he should be directed to its home page like if user writes www.microsite1.domain.com, then the site should point to page ~/Microsite/Home.aspx?value=microsite1, and when the user accesses www.microsite1.domain.com/about.aspx then i should able to get the argument value1=about.
The first step is to place the subdomain name in the DNS Host Server. To do that you need to manipulate the dns files. For example if you use BIND as DNS server you go and open the text file that keep your DNS configuration eg: "c:\program files\dns\var\mysite.com" and there you add a line as
subdomain.mysite.com. IN A 111.222.333.444
Also you change the ID of the file to give a message to BIND to update the subdomains.
Second step is to redirect the new subdomain to the correct directory. You do that on the protected void Application_BeginRequest(Object sender, EventArgs e) on Global.asax using rewritepath
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (HttpContext.Current.Request.Url.Host.StartsWith("subdomain."))
{
// here you need to find where to redirect him by reading the url
// and find the correct file.
HttpContext.Current.RewritePath("/subdomain/" + Request.Path, false);
}
// .... rest code
}
Its not so easy, not so hard... maybe there are some more minor issues like permissions to write to dns. Also you need to know dns, read the manual about.

Resources