Get the port number of your Web Application Zone using server side object model

Although it seems pretty easy to get your web application’s port number from IIS or Central Admin, I didn’t find enough info on how to get the port number from server side object model. I was trying to customize the Authenticate.aspx application page where I had already written code to check users permission in a specific group of another web application. In the end, I was able to get a really simple method which is the following piece of code:

int webPort=SPContext.Current.Site.WebApplication.IisSettings[Microsoft.SharePoint.Administration.SPUrlZone.Default].ServerBindings[0].Port; if (webPort==80) { //check user permission for a site collection which is using the web app on port 80 ... ... }

else { //check the user permission for rest of the web apps SPUtility.EnsureAuthentication(); SPUtility.Redirect(spWeb.Url, SPRedirectFlags.UseSource, Context); }

If you look at the code, you’ll easily understand I was actually trying to check the user permission for the web application which is using Port 80 and you can write your server side code there to check any user’s permission or group permission etc. Notice that, here I am actually checking the default zone’s port number for the web application. If you have multiple zones, or else if you have extended your web application on other zones which have different ports, then you have to specify  one from the below under WebPpplications.IisSettings property:

SPUrlZone.Custom,
SPUrlZOne.Default,
SPURlZone.Internet,
SPUrlZone.Intranet
SPUrlZOne.Extranet

Now, what if you want to create a method, which will get the port number of web application and later on you can call that method from anywhere; you can do that too. The code is given below:

int GetPortNumber(Microsoft.SharePoint.Administration.SPWebApplication application)
{
int result = 0;
Microsoft.SharePoint.Administration.SPIisSettings setting=null;
if (application.IisSettings.TryGetValue(Microsoft.SharePoint.Administration.SPUrlZone.Default, out setting))
{
if (null != setting)
{
var serverBindings = setting.ServerBindings;
if (0 < serverBindings.Count)
{
Microsoft.SharePoint.Administration.SPServerBinding serverBinding = serverBindings[0];
result = serverBinding.Port;
}
}
}
return result;
}
Advertisement