0

I am actually moving an old project which is classic webservice in C# (ASMX) to WebAPI asp.net core 3.1

Since without any previous experience in Web API I'm facing some challenges in conversion.

Here is a code snippet I was using ASMX to get current user

 PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

 UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(ctx, 
 HttpContext.Current.User.Identity.Name);
 UserName = userPrincipal.DisplayName;

What I did is created a class file kip.cs and in an empty method I pasted this code.

But HttpContext highlights of an error saying Httpcontext not exists in this context. So what should I use to get it work

Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132

1 Answers1

3

HttpContext used to be a static sealed class, which was horrendous for testing. In ASP.NET Core, it is now scoped to the request (i.e. it is instantiated at the beginning of the request and disposed at the end of the request). As such, there's no such thing as HttpContext.Current because 1) it's not a static any more and 2) it doesn't exist outside the request pipeline.

In order to access the current (i.e. in scope) HttpContext instance, you must inject IHttpContextAccessor. That's a singleton which must additionally be registered with the service collection if you need to make use of it:

services.AddHttpContextAccessor();

Then, in your library class, you'd simply do something like:

public class MyClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MyClass(IHttpContextAccesor httpContextAccesor)
    {
        _httpContextAccesor = httpContextAccessor;
    }

    ...
}

And later:

// WARNING: may be null
var httpContext = _httpContextAccessor.HttpContext;

As I said previously, HttpContext only exists within the request pipeline, so you can only access it in code that is running in that scope. If you try to get it in code that is running not as a direct result of a request coming into your an ASP.NET Core app, then it will simply be null. As such, you should do proper null checking to ensure you can safely use it.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444