B
B
BloodyBlade2017-05-13 17:25:26
ASP.NET
BloodyBlade, 2017-05-13 17:25:26

Why does NullReference fail when trying to get AuthenticationManager via OwinContext?

Hello! When working with asp.net identity, I ran into a problem. Moved work with asp.net identity from asp.net mvc project (UI) to a separate project (BLL), created a field to get authenticationManager:

private IAuthenticationManager autenhticationManager => HttpContext.Current.GetOwinContext().Authentication;

In the future, I use it to obtain information about the current user.
Locally, everything works fine, authentication passes, but after publishing to the hosting, when trying to authenticate, everything falls down, the following messages fall into the logs:
2017/05/12 20:05:35.385 | fatal | System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.HttpContextExtensions.GetOwinEnvironment(HttpContext context)
at System.Web.HttpContextExtensions.GetOwinContext(HttpContext context)
at BusinessLogic.Service.UsersService.get_authenticationManager()
2017/05/12 20:05:35.479 | fatal | System.NullReferenceException: Object reference not set to an instance of an object.
at BusinessLogic.Service.UsersService.get_authenticationManager()
at BusinessLogic.Service.UsersService.d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---

Apparently OwinContext returns null, but I can't figure out why.
I thought it was because the Sturtup file is in the UI project, but after moving it to the BLL, nothing has changed.
I looked all over and couldn't find anything that would help me. Perhaps someone faced such a problem? I would appreciate any help or guidance, thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anvar Shakhmaev, 2017-05-13
@RxR

you need to configure Owin like this (depends on the implementation of the AuthenticationManager class):

[assembly: OwinStartup(typeof(YourAppName.App_Start.Startup))]
namespace YourAppName.App_Start
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext<EF_DbContext>(EF_DbContext.Create);
            ...
            app.CreatePerOwinContext<AuthenticationManager>(AuthenticationManager.Create);
            ...
        }
    }
}

In this case, the AuthenticationManager must implement the Create method, thus:
public static AuthenticationManager Create(IdentityFactoryOptions<AuthenticationManager> options, IOwinContext context)
{
    var manager = new AuthenticationManager(context.Get<EF_DbContext>());
    return manager;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question