Description
Aplication type: WEB API
.NET Framework: 4.5
MVC: 5
I need caller host ip in my custom action filter and then in action. On some enviroments we have configured load balancer which stores caller ip in header "HTTP_X_FORWARDED_FOR". I nedd my code works with LB or without.
CODE
Filter
using System.Collections.Generic;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace FAPTest.TestApp.ActionFilters
{
public class AccessControlFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
string ip = HttpContext.Current.Request.UserHostAddress;
string sourceIp = HttpContext.Current.Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR");
string ipAddress = ip;
if (!string.IsNullOrEmpty(sourceIp))
{
ipAddress = sourceIp;
}
actionContext.Request.Properties.Add(new KeyValuePair<string, object>("ipAddress", ipAddress));
}
}
}
Controller
using System.Web.Http;
namespace FAPTest.TestApp.Controllers
{
public class TestController : ApiController
{
[HttpGet]
public string Test()
{
object o = null;
string ipAddress = null;
if (Request.Properties.TryGetValue("ipAddress", out o))
{
ipAddress = (string)o;
}
return ipAddress;
}
}
}
Filter registration:
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using FAPTest.TestApp.ActionFilters;
namespace FAPTest.TestApp
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.Filters.Add(new AccessControlFilter());
}
}
}
Questions
Is this code safe?
What can I improve?
Are there some pitfals?