Reputation: 311
I'm building an app using DotVVM framework (ver 1.1.9) using AspNet.Core and .NET Framework 4.7.1. At some point I need to log remote user's IP address. Is there a way to get it inside the ViewModel? I've seen many tutorials
There is a property Context
in ViewModelBase that has property HttpContext
but it's some build-in IHttpContext
interface, not the proper HttpContext
.
However I found out that I can cast existing IHttpContext
to DotvvmHttpContext
which contains property OriginalContext
that indeed seems to be the one I was looking for.
var remoteAddr = ((DotvvmHttpContext)Context.HttpContext).OriginalContext.Connection.RemoteIpAddress;
So the question is, if this is "safe" approach or is there any other "proper" way to either access original AspNet HttpContext or the remote IP Address directly?
Upvotes: 0
Views: 265
Reputation: 510
Yes, this is safe approach as long as you are only going to run the application on Asp.Net Core. If you'd switch to OWIN hosting for some reason, it would throw an invalid cast exception.
Also note that there is a helper method for getting the Asp.Net Core http context, Context.GetAspNetCoreContext().Connection...
might be a bit more comfortable. As you can see from the source code, it's basically the same as your code: https://github.com/riganti/dotvvm/blob/d623ae5ddf57ecf3617eb68454d546f675b64496/src/DotVVM.Framework.Hosting.AspNetCore/Hosting/AspNetCoreDotvvmRequestContextExtensions.cs#L13
Upvotes: 1
Reputation: 387587
Looking at the source for IHttpContext
that is exposed in the DotvvmViewModelBase
, there does not seem to be a good way to access the connection information. I was hoping that the IHttpRequest
might expose the remote IP address but that also isn’t the case.
You have to rely on accessing the original HttpContext
from ASP.NET Core here to access that information. If you run on ASP.NET Core (instead of OWIN), then it should be totally save to cast the context to DotvvmHttpContext
so that you can access the underlying HttpContext
.
So yeah, your solution seems just fine here:
var originalHttpContext = ((DotvvmHttpContext)Context.HttpContext).OriginalContext;
Upvotes: 0