0

I want to access JwtHelper from ExceptionHelper. But problem is ExceptionHelper must be static. And so, we can't create constructor and not access jwtHelper Method. How can I achieve access jwHelper from ExcewptionHelper.

Startup.cs

 public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddMvc();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddDbContext<MyDbContext>();
    services.AddTransient<IUnitOfWork, UnitOfWork>();
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
     app.UseExceptionHandler(builder => builder.Run(async context =>
     {
         var error = context.Features.Get<IExceptionHandlerFeature>();

         context.Response.AddApplicationError(error);
         await context.Response.WriteAsync(error.Error.Message);
     }));

    app.UseHttpsRedirection();
    app.UseMvc();
}

ExceptionHelper.cs

    public static class ExceptionHelper
    {
        public static async Task AddApplicationError(this HttpResponse response)
        {
            Log log = new Log();
            log.UserId = jwtHelper.GetValueFromToken(token, "UserId");??????
            //in this line I can't access jwtHelper.
        }
    }

JwtHelper.cs

 public class JwtHelper : IJwtHelper
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        public JwtHelper(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        public string GetValueFromToken(string stream, string propertyName)
        {
            var jwt = httpContextAccessor.HttpContext.Request.Headers["Authorization"];

            var handler = new JwtSecurityTokenHandler();
            var tokens = handler.ReadToken(stream.Replace("Bearer ", "")) as JwtSecurityToken;
            return tokens.Claims.FirstOrDefault(claim => claim.Type == propertyName).Value;
        }
    }
3
  • How, I can do this? Inject JwtHelper in wherever you need it. Commented Oct 22, 2018 at 12:28
  • Is JwtHelper registered in your DI container? Perhaps attach your startup class so we can see your registrations. Commented Oct 22, 2018 at 12:30
  • JwtHelper hasn't got interface. That is only class. This code is giving error with this state. @mjwills Commented Oct 22, 2018 at 12:33

2 Answers 2

1

If I were you I would register JwtHelper with a Interface known as IJwtHelper. It would look like this then

public class JwtHelper : IJwtHelper
{
    private readonly IHttpContextAccessor httpContextAccessor;

    public JwtHelper(IHttpContextAccessor httpContextAccessor)
    {
        this.httpContextAccessor = httpContextAccessor;
    }

    public  string GetValueFromToken(string propertyName)
    {
        var jwt= httpContextAccessor.HttpContext.Request.Headers["Authorization"];
        // I can't access httpContextAccessor in this line.

        var handler = new JwtSecurityTokenHandler();
        var tokens = handler.ReadToken(jwt) as JwtSecurityToken;
        return tokens.Claims.FirstOrDefault(claim => claim.Type == propertyName).Value;
    }
}

public interface IJwtHelper
{
    string GetValueFromToken(string propertyName);
}

In my startup.cs class I would then do

 services.AddSingleton<IJwtHelper, JwtHelper>();

And then when you want to access your helper I would inject IJwtHelper

  private IJwtHelper _jwtHelper;
  public SomeConstructerOnClass(IJwtHelper jwtHelper)
    {
        _jwtHelper = jwtHelper;
    }
 public void SomeMethod(string property) {
    var token = _jwtHelper.GetValueFromToken(property);
    //Do something with token
    }

where _jwtHelper is field of type IJwtHelper.

You will then be able to use GetValueFromToken quite fine anywhere you inject IJwtHelper

UPDATE

Your problem is that ExceptionHandler is Static , implement an interface and add it to container

  public class ExceptionHelper : IExceptionHelper
{
  private IJwtHelper _jwtHelper;
  public ExceptionHelper(IJwtHelper jwtHelper)
{
    _jwtHelper = jwtHelper;
}
    public async Task AddApplicationError(this HttpResponse response)
    {
        Log log = new Log();
        log.UserId = _jwtHelper.GetValueFromToken(token, "UserId");??????

    }
}
public interface IExceptionHelper
{
Task AddApplicationError( HttpResponse response);
 }

Then

 services.AddSingleton<IExceptionHelper, ExceptionHelper>();

Now You will be able to inject it into your Configure method like so

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IExceptionHelper exceptionHelper)
{
 app.UseExceptionHandler(builder => builder.Run(async context =>
 {
     var error = context.Features.Get<IExceptionHandlerFeature>();
     //Resolved and available!
     exceptionHelper.AddApplicationError(error);
     await context.Response.WriteAsync(error.Error.Message);
 }));

app.UseHttpsRedirection();
app.UseMvc();

}

If you follow me advice above from my initial response and my update everything should be fine and registered nicely in your container :)

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for your reply. But, reason of not using Dependency injection is "SomeConstructerOnClass" has static class. So, i can't access JwtHelper from method in SomeConstructerOnClass. I edited my question. Can you check my question again? @cl0ud
@HasanOzdemir i dont see how you are gonna get around this without using DI , IHttpContextAccessor is part of the DI container hence why the implementing class will require to be a part of the container aswell. Is JwtHelper registered ?
In your code, "SomeMethod" is not static method. But in my new edited question, "AddAuditLog" method is static. This is the reason of problem. "AddAuditLog" method must be static. But I can't access jwtHelper from static method. @cl0ud5. So, I'm looking for solution to this problem.
@HasanOzdemir Im unsure how your code interacts with other classes, if you provide the full flow for me from start to finish I can perhaps help you restructure it to help you . Im feeling the issue is that you are wanting to combine non registered classes with registered classes from a static context which is why you are running into problems.
@HasanOzdemir thank you , I will update my answer now
|
0

You'll have to instantiate the JwtHelper class in order to access the instance variable (httpContextAccessor) from another class. Static methods, like GetValueFromToken, cannot access instance variables.

1 Comment

Did you mean that, I create IJwtHelper interface and then inject it when i need jwthelper. Is it true? @Sean

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.