79095010

Date: 2024-10-16 16:42:13
Score: 0.5
Natty:
Report link

I finally got this working. Two changes were needed, see below.

First, use IHttpContextAccessor instead of UserService:

    public class TestService
    {
        public string Username { get; set; }

        public TestService(IHttpContextAccessor httpContextAccessor)
        {
            Username = httpContextAccessor.HttpContext?.User?.Identity?.Name ?? "unknown";
        }

        //public TestService(UserService userService)
        //{
        //    Username = userService.Username;
        //}
    }

This handled the issue in dev and when run directly in Kestrel. However, it still did not work in IIS.

To make it work in IIS, enable "Web Sockets" in IIS, see this SO post: WebSockets must be enabled in IIS

I am not sure that this is the correct way of doing this and I still do not understand why my initial solution does not work: why DI sends blank UserService to TestService.

I have seen various information about using HttpContext in Blazor. If I understand this page correctly: HTTP Context in ASP.NET Core, it seems that it is mainly a problem with interactive components. I would prefer a working solution that does not have this potential issue.

Feel free to suggest a better way and I will gladly accept that solution instead!

Reasons:
  • Blacklisted phrase (1): did not work
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (0.5):
Posted by: Zek