How can I programatically limit access to a Webser

2019-04-14 19:21发布

问题:

I am writing a traditional ASMX webservice using C# with .Net 2.0 for deployment on IIS. The webservice will be deployed in a shared hosting environment where each client has their own copy of the application sitting in a separate virtual directory (I know, I know - it's a legacy app). There will be an individual copy of the Webservice sitting in each virtual directory.

As the Webservice could potentially do some powerful things, I would like to optionally limit access to it to certain IP addresses. Doing this in the firewall isn't a very good option as it is only the webservice that should be limited and not the rest of the website - and it is on a per-virtual-directory level.

Can I programmatically read the IP address of the requestor and compare it to a list so I can reject calls from other addressess? Are there any major pitfalls to this?

Thanks

回答1:

Yes you can do it easily.

[WebMethod]
public bool IsAlive()
{
     string callingAddress = HttpContext.Current.Request.UserHostAddress;
     return (callingAddress == allowedAddress);
}

The only pitfalls are the maintenance of the list of IP addresses.

It's also worth noting that you can configure IP address access control on a per web application basis from within IIS. I have used both approaches at different times and it really just comes down to how you want to maintain the list of authorised IP addresses.