Although I do not know how do create the object of ServiceModel class and use it, I provide a sample code assuming you want to log the username.
Below is a sample of ASP.NET Core 6.0 MVC based on Microsoft document Access HttpContext from custom components:
UserRepository class
Assume this is your ServiceModel class.
namespace MvcCore6App3.Libraries
{
public class UserRepository : IUserRepository
{
// inject IHttpContextAccessor object by DI
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly ILogger<UserRepository> _logger;
public UserRepository(IHttpContextAccessor httpContextAccessor,
ILogger<UserRepository> logger)
{
_httpContextAccessor = httpContextAccessor;
_logger = logger;
}
public void LogCurrentUser()
{
// Get login user name
var username = _httpContextAccessor.HttpContext?
.User.Identity?.Name;
if (username != null)
{
_logger.LogInformation($"{username} access on {DateTime.Now}");
}
else
{
_logger.LogInformation($"anonymous access on {DateTime.Now}");
}
}
}
public interface IUserRepository
{
public void LogCurrentUser();
}
}
Program.cs
Note that ASP.NET Core Identity is enabled and username is obtained form it.
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using MvcCore6App3.Data;
using MvcCore6App3.Libraries;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddControllersWithViews();
// 2024/9/19 Add IHttpContextAccessor and UserReposirty to DI container
builder.Services.AddHttpContextAccessor();
builder.Services.AddTransient<IUserRepository, UserRepository>();
// Code omitted below
Controller
using Microsoft.AspNetCore.Mvc;
using MvcCore6App3.Models;
using System.Diagnostics;
namespace MvcCore6App3.Controllers
{
public class HomeController : Controller
{
private readonly Libraries.IUserRepository _userRepository;
public HomeController(Libraries.IUserRepository userRepository)
{
_userRepository = userRepository;
}
public IActionResult Index()
{
// get current user name and log it outside of Controller
_userRepository.LogCurrentUser();
return View();
}
// code omitted
}
}
Result