Bir önceki yazımda web api metodlarımıza gelen tüm isteklere cevap dönüyorduk. Peki sadece önceden tanımladığımız iplerin web api metodlarına erişmesini nasıl sağlayabiliriz.

Öncelikle projemize sağ tıklayıp Add -> Class deyip Class ismine IPValidationAttribute yazıyoruz.
Ardından aşağıdaki kod parçasını oluşturduğumuz class içine koplayaıp yapıştıralım.

public class IPValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var ips = new List<string>();
ips.Add("127.0.0.1");
ips.Add("::1");

var context = actionContext.Request.Properties["MS_HttpContext"] as System.Web.HttpContextBase;

string userIP = context.Request.UserHostAddress;
try
{
ips.AsQueryable().First(x => x == userIP);
}
catch (Exception)
{
actionContext.Response =
new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
Content = new StringContent("Tanımlanmayan IP Adresi")
};
return;
}
}
}

Son olarak Global.asax içindeki Application_Start() metoduna

GlobalConfiguration.Configuration.Filters.Add(new IPValidationAttribute());

kod parçasını ekliyoruz. Çalıştıdığımızda web api sadece localhost tarafından gönderilen isteklere cevap dönecektir. Hangi ip adreslerine izin vereceksek OnActionExecuting() metodu içindeki ips listesine bu ipleri eklemeiz gerekmektedir.