You could create a new service
.
public class MyHttpContextService : IMyHttpContextService
{
IHttpContextAccessor _httpContext;
public MyHttpContextService(IHttpContextAccessor httpContext)
{
_httpContext = httpContext;
}
public string CheckUserRoles()
{
try
{
var currentUser = _httpContext?.HttpContext?.Session?.GetCurrentUser<SessionContext>();
if (currentUser != null)
{
if(currentUser.Roles.Any())
{
if(!currentUser.Roles.Contains("Administrator"))
{
if(currentUser.Roles.Contains("Doctor"))
{
//do something here
}
else if (currentUser.Roles.Contains("Patient"))
{
//do something else here
}
}
}
}
else
{
// if currentUser == null
}
}
catch (Exception ex)
{
// exception handling
}
}
}
Notice the line
var currentUser = _httpContext.HttpContext.Session.GetCurrentUser<SessionContext>();
is replaced by
var currentUser = _httpContext?.HttpContext?.Session?.GetCurrentUser<SessionContext>();
Create appropriate interface
.
public interface IMyHttpContextService
{
string CheckUserRoles();
}
In this example string
is return type, but it does not need to be.
Finally, register this service using line
services.AddScoped<IMyHttpContextService, MyHttpContextService>();
where services
is
IServiceCollection services
Instead of AddScoped
, you could use AddTransient
, or AddSingleton
. More about objects' lifetime and dependency injection. These three keywords determine the lifetime of an object, or in this case, of service.
Registration is starting in Startup.cs
(but to be honest, everything is starting in Startup.cs
, hence the name). More about Startup.cs. In other words, in Startup.cs
call method
public void ConfigureServices(IServiceCollection services)
which is called by runtime.
Inside method ConfigureServices
call another one, for instance MapInterfaces
, for interface mapping and pass it services
. Method MapInterfaces
will be a static
method inside ServiceExtensions.cs
.
public static void MapInterfaces(IServiceCollection services)
{
services.AddScoped<IMyHttpContextService, MyHttpContextService>();
}
Even better is to create an extension method More about extension methods.
ServiceExtensions.cs
is a static
class, which is a condition for creating extension method. Extension method also needs to be static
. This would be the methods signature
static void MapInterfaces(this IServiceCollection services)
Of course, don't forget the access modifier (at least the same visibility as the ServiceExtensions.cs
class). Notice this
keyword.
Extension method MapInterfaces
from ServiceExtensions.cs
is then called inside ConfigureServices
method from Startup.cs
like this
services.MapInterfaces();
In the end, whenever you need method CheckUserRoles
, call it like this
_myHttpContextService.CheckUserRoles();
EDIT: You've changed the implementation of method, but that doesn't change the way you could do the rest of solution.