1

When my web request is run, some properties that are in the Properties property of HttpRequestMessage are from the System.Web namespace, although the application I am developing is .NET Core 2 Azure function.

I would like to use one object from the collection, MS_HttpContext which is of type System.Web.HttpContextWrapper. Is it possible to use this object and somehow cast to it? This object seems to be from standard .NET framework.

[FunctionName("Track")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "track")]HttpRequestMessage req, TraceWriter log, ExecutionContext context)
{
    // HttpContextWrapper is from System.Web, so this does not work
    var ctx = (HttpContextWrapper)req.Properties["MS_HttpContext"] 
}

EDIT: my question is slightly different than my previos question (Get remote IP address in Azure function), because it asks how can classes from System.Web namespace be accessed from a .NET Core application. Although I admit the desired result is the same in both questions, to get the remote IP address.

Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
  • You asked a similar question here https://stackoverflow.com/questions/53211824/get-remote-ip-address-in-azure-function with an answer. What is the intent of this questions and the proposed solution below? – Sebastian Achatz Nov 09 '18 at 15:08
  • I did not make the solution using `HttpRequest` as a parameter instead of `HttpRequestMessage` work for me, although it seems to be working for other people and in other examples. This is another solution that seems to be working. – Martin Staufcik Nov 09 '18 at 15:12
  • If that is the same intent maybe you should try to got further on this on the other question (https://stackoverflow.com/questions/53211824/get-remote-ip-address-in-azure-function) instead of opening new questions with the same context. maybe someone can help with your problem but please stay on the thread / question – Sebastian Achatz Nov 09 '18 at 15:15
  • Possible duplicate of [Get remote IP address in Azure function](https://stackoverflow.com/questions/53211824/get-remote-ip-address-in-azure-function) – Sebastian Achatz Nov 09 '18 at 15:16

1 Answers1

1

Alright, not that I know much how this works, but reflection seems to work:

private static string GetRemoteIpAddress(HttpRequestMessage req)
{
    if (req.Properties.ContainsKey("MS_HttpContext") == false)
    {
        return null;
    }

    var httpContext = req.Properties["MS_HttpContext"];

    var pi = httpContext.GetType().GetProperty("Request");
    var request = pi.GetValue(httpContext);

    pi = request.GetType().GetProperty("UserHostAddress");
    var address = pi.GetValue(request);

    return address == null ? null : address.ToString();
}
Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63