Being relatively new to ASP.NET Core and Razor Pages, I'm still trying to become familiar with the best approach to handle certain logic.
I have a model that encapsulates every property or model I would liked to have readily available on every razor page.
As I have it now, I have a in-memory model called CurrentEnvironment with a few properties and objects that I'll access from various pages.
CurrentEnvironment Snippet:
public class CurrentEnvironment {
public string Url {get;set;}
public string IPAddress {get;set;}
Public AppUser User {get;set;}\
//.....
}
Each Razor Page implements BasePageModel which itself implements PageModel. If the page requires Authentication, then there is a SecurePageModel with the [Authorize] filter that implements BasePageModel
BasePageModel:
public CurrentEnvironment CurrentEnvironment { get; set; } = new CurrentEnvironment();
public override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
CurrentEnvironment.IPAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString();
CurrentEnvironment.Url = context.HttpContext.Request.GetDisplayUrl();
return base.OnPageHandlerExecutionAsync(context, next);
}
SecurePageModel snippet:
[Authorize]
public class SecurePageModelAsync : BasePageModelAsync
{
//......
public override Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
{
CurrentEnvironment.User = _userManager.GetUserAsync(HttpContext.User).Result;
return base.OnPageHandlerExecutionAsync(context, next);
}
}
My question(s):
- Is there a better way to handle this and produce the same results?
- I'm guessing I want to create a service to handle
CurrentEnvironmentmaybe? If so, how would I populate the service? Middleware?