Getting IIS Websites' Domain names - c#

I've created a web application to list all websites on IIS with their names, ports and physical paths. it's also supposed to get the IIS websites domain names. the application is installed on IIS and all functions work great except for returning domain names.
I wrote the below code and it returned "localhost:8183" for all websites. 8183 is the application's port itself.
Request.Url.Scheme + "://" + Request.Url.Authority +
Request.ApplicationPath.TrimEnd('/') + "/";here
then I tried this one and it just returned "localhost" instead of domain names.
HttpContext.Current.Request.Url.Host;
I'm so curious to know where I'm going wrong. please let me know if any further information is needed.

A web server does not actually know what domains it can serve. It knows what domain was in the request headers in the thread for that request, but you can set up any domain you like to point to any server's IP address and the server will accept it.
If you have set up bindings by domain (using Server Name Indication), you can get that information from the objects in Microsoft.Web.Administration ( for each site in ServerManager.Sites, for each Binding in site.bindings, if Binding.Protocol = http or https and Binding.Host !="" then write out Binding.Host) but that won't tell you about any domains that aren't in bindings.

If you use request object it will only give details about the website where your code is running. You need to use Directory Services to connect to IIS and do you work.
[From already answered question]- Here's an article explaining how this could be done using classes from the System.DirectoryServices namespace as well as the Microsoft.Web.Administration namespace which was introduced with IIS 7.

You can use below code to get the Domain name of current server:
System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName
or you can use below code to get current user's domain:
System.Security.Principal.WindowsIdentity.GetCurrent().User. (string value)
Then you can trim it.
Happy coding.

Related

How do I stop other domains from pointing to my domain?

I recently found out that there are other domain names pointing to my website (that don't belong to me) and I was wondering how people can stop/prevent this from happening. I'm hosting this on peer1 using IIS and I'm using ASP.NET C#.
Can I use an HttpModule or some other code to reject domain names that aren't mine?
Is there a better way?
You should activate name-based virtual hosting and only show your real website for the desired domain names. For all other names, you can display a suitable error message.
Details: Your webserver is contacted by its IP address. There is nothing you can do to stop that. Anyone can say, "connect to that IP address". For instance, anyone can register new domain names to point to your server's IP address. However, inside the request, there is a field Host with a name like www.example.com.
Upon receiving the request, your server may choose to inspect the Host field and deliver different content depending on that value. In the simplest case, the server ignores the field entirely and always prints out the same content. But in a more sophisticated set-up, so called "name-based (virtual) hosting", the server chooses the content depending on the hostname.
This is how shared webhosts work: There's a single server, but depending on the requested hostname it spits out a different website for each name.
Therefore, if you want to tie your server content to your hostname, you have to tell your server to produce your website only for your desired name, and to produce a different (error) website for all other cases.
In Apache this is trivial to configure, just check their documentation; for IIS I wouldn't know but I imagine it's equally simple.
If your hosting environment is IIS and you have admin access to it. Set your default website to show an error page and then create a new site with the host header matching your domain to point to your website.
This is my solution. It really works fast and solved my problem.
Insert this code in your .htacces
RewriteCond %{HTTP_HOST} !^www.higueyrd.com$
RewriteRule ^/?(.*) http://www.higueyrd.com/$1 [QSA,R=301,L]
Just put your domain.
In IIS there is a setting called bindings that allows you to select which hostnames your website will respond to. This feature allows an instance of IIS to host mulitple websites on a single IP address.
If you want your site to only work for http://example.com/ and http://www.example.com/, you should set the bindings to only work for "example.com" and "www.example.com".
The exception here is if you are using SSL. If you are, IIS cannot determine the hostname and you will most likely have to use a dedicated IP address for your site. In that scenario, user608576's solution will work. Although, I would put that code in your Global.asax file:
<%# Application Language="C#" %>
<script runat="server">
void Application_BeginRequest(Object sender, EventArgs args)
{
HttpRequest request = HttpContext.Current.Request;
HttpResponse response = HttpContext.Current.Response;
if( (request.Url.Host != "example.com") && (request.Url.Host != "www.example.com") )
{
response.Clear();
response.Write("Unauthorized domain name: " + request.Url.Host);
response.End();
}
}
</script>
As a temporary fix you can do this . May be on home page load or BeginRequest .
if(!Request.Url.Host.ToLower().contains("mysite.com")){
Response.Redirect("error.html");
}
If i remember right when i last check my sites cpanel i saw a feature that stopped redirections to my domain if checked. I´m using Hostso as my host so check their test cpanel for it.
Hope it helps alittle atleast :)
Fredrik wirth
if you want to handle in code then do it in Global.asax in BeginRequest as below
void Application_BeginRequest(object sender, EventArgs e)
{
if (!context.Request.Url.Host.ToLower().Equals("www.mydomain.com"))
{
context.Rewritepath("/invalidpage.aspx");
}
}
The other simple way is to specify a host headers in IIS for your website.
http://technet.microsoft.com/en-us/library/cc753195(v=ws.10).aspx
Note: I am writing through my mobile so consider spelling mistakes

Does Request.Url.Host include the subdomain?

e.g. for mail.google.com would it return google.com or mail.google.com?
I can't actually test it myself
It does include subdomain (e.g. mail.google.com)
You can save yourself from the headache of waiting for answers by reading documentation on Msdn.
A String that contains the host name. This is usually the DNS host name or IP address of the server.
If the requested DNS record is a subdomain, that's the record it will return. Subdomains are still there own records in a zone file, so its not going to return just the root domain because that's not the same record, nor request.
I was also curious as to why you couldn't test this, but if its because of the lack of an internet connection (maybe you're posting from mobile I don't know) you can add your own records to the Windows HOSTS file and test locally.

Is it possible that Request.ServerVariables["HTTP_HOST"].ToString() can return a different host than what I see in the url bar

Say I have a remote page accessed through http://www.mypage.com/test.aspx. On that page I use the code Request.ServerVariables["HTTP_HOST"].ToString(). Is it possible that when I access the page the code can return a different url than that which I see in the url bar which is http://www.mypage.com/test.aspx? Any help would be appreciated. Thanks.
You could see any name that IIS has bound to your web instance. So, if your server is called "server1" and the IP address is 123.123.123.123 and all three of those are bound to your instance of IIS, you could see any of those values.
To look up what names are bound, open "Internet Information Services (IIS) Manager" (start, Administration tools), expand the tree till you see your sites. Find the one you are using. Right-click and choose "Bindings". Edit each of the bindings in the list. If they all say [IP address:] "All Unassigned", then your HTTP_HOST could be 1. the WWW address that you have configured via DNS, 2. the machine name 3. the IP address(es).
try to use:
HttpContext.Current.Request.ServerVariables["SERVER_NAME"]
i hope that this will be work.
I was also facing the issue with HttpContext.Current.Request.ServerVariables["HTTP_HOST"] and figured it out. The best way to retrieve the hostname is "HttpContext.Current.Request.Url.Host". It resovled my issue.
Thanks,
Raj
It is possible, yes. A isapi_rewrite module could modify the value of HTTP_HOST before your own code is able to inspect it.
Someone has already mentioned local rewriters (isapi_rewrite), but there are also remote ones, like an ISA Server publishing your server. It's a configuration thingie to send original host headers (what the client entered), or the ones entered in the publishing settings.

Wrong host returned using HttpContext.Current.Request.Url.Host

We have multiple domains for one of our websites.
e.g. mydomain-uk.com and mydomain.co.uk
I have a handler which creates an XML sitemap and it uses HttpContext.Current.Request.Url.Host to retrieve the host site.
When my browser is on mydomain.co.uk/handler it retrieves mydomain-uk.com as the host
How can I ensure it always retrieves mydomain.co.uk ?
Is there a preference order configured somewhere on the server?
The host is get it from the URL on the request, and this is logical, you can not change this.
To solve this, create a static variable with your URL name, even better place it on your web.config, and just get this variable and not the Url.Host
Hope this help
Don't point all of your domains at the website. Have the extra domains perform a 301 redirect to the main domain name. This will also help resolve confusion by search engines when they try to resolve your site as to which site is the original source of your content, and will prevent inbound links from other websites from using a mixture of domains which will only exacerbate the problem.
Don't forget that HttpContext.Current.Request.Url.Host is simply going to return whatever HOST was requested at the time it happened. If the client requested something else, HttpContext.Current.Request will reflect this.

SPItemEventReceiver Context SiteId/WebUrl Incorrect

I have created a SharePoint Event Receiver, that fires on Item Update.
The receiver needs access AfterProperties and ListItem.
When firing the event receiver from a SharePoint web application using an IP address (http://10.0.4.50/sites/), it throws a FileNotFoundException, when accessing SiteId And WebUrl in SPItemEventProperties.
The Web application at http://10.0.4.50/sites/companyName could not be found. Verify that you have typed the URL correctly.
When firing the event receiver using the hostname, specified at setup of Site Collection http://computerhostname/sites/companyName. This works fine, no exception is thrown.
//Combine Both AfterProperties And ListItem
var ListProperties = new List<KeyValuePair<string, object>>();
ListProperties.AddRange(properties.AfterProperties.ToKeyValue());
ListProperties.AddRange(properties.ListItem.ToKeyValue(p => !p.Sealed));
var AvaliableProperties = ListProperties.Distinct(new KeyValueComparer<object>());
This isn't necessarily a SharePoint problem, but is most likely down to the way that IIS is configured on the host. A particular site can be "bound" to an IP address and a host name, and if the host name isn't present in the HTTP GET sent by the browser then IIS will return a 404 NOT FOUND.
You can verify this by using a browser to see whether you can access the site by IP address.
You can add additional bindings if necessary, but there can only be one "default" binding per IP address, so only one site can be present at (in your case) 10.0.4.50.
A possible way around the situation where multiple sites are present but you can't use a hostname might be to add a binding to a port other than port 80 for this IP, so your URL would become something like http://10.0.4.50:8080/sites/companyName.
This is not just an IIS problem, but Sharepoint related as well. A lot of referencing in SharePoint is done by using a url as a starting point (just look at the constructor of SPSite). The url is then compared to known url's in SharePoint's Config database. (and ofr files etc in the site's content database).
SharePoint uses a system called Alternate Access Mappings to assign different urls to a Web Application's "Zones" (default, intranet, internet, ... custom definition). If it does not find the 'exact' Url, internally stuff will fail (And especially search is very "Url sensitive").
Then comes the IIS part into play: Since IIS probably has no other site running on the 80 port, and without a specific hostheader (so it defaults to machinename), or with the hostheader set to the machine name, IIS will pick up the request and since SharePoint is tied into this webapp, SharePoint will try to process it, looks up the url, Sharepoint does not find the Url and thne "breaks".
The no hostheader occurs when you leave the hostheader field empty when you create a new web app in SharePoint.

Categories

Resources