ASP.NET WebAPI Identity 2 - error with GetOwinContext on user registration / registration method

I have a WebAPI 2.1 application and I am having a user registration problem. I put a breakpoint on the first line of the Register method, but it was not hit. Instead, it fails in the area below:

    public ApplicationUserManager UserManager
    {
        get
        {
            var a = Request; // this is null !!
            return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    [AllowAnonymous]
    [Route("Register")]
    [ValidateModel]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {

        var user = new ApplicationUser() { // <<<<< Debug breakpoint here never reached
            Email = model.Email, 
            FirstName = model.FirstName, 
            LastName = model.LastName,
            OrganizationId = 1,
            OrganizationIds = "1",
            RoleId = (int)ERole.Student,
            SubjectId = 1,
            SubjectIds = "1",
            UserName = model.UserName
        };




System.ArgumentNullException was unhandled by user code
  HResult=-2147467261
  Message=Value cannot be null.
Parameter name: request
  Source=System.Web.Http.Owin
  ParamName=request
  StackTrace:
       at System.Net.Http.OwinHttpRequestMessageExtensions.GetOwinContext(HttpRequestMessage request)
       at WebRole.Controllers.AccountController.get_UserManager() in c:\G\abr\WebRole\Controllers\Web API - Data\AccountController.cs:line 50
       at WebRole.Controllers.AccountController.Dispose(Boolean disposing) in c:\G\ab\WebRole\Controllers\Web API - Data\AccountController.cs:line 376
       at System.Web.Http.ApiController.Dispose()
       at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.SelectAction(HttpRequestMessage request, IHttpRouteData routeData, HttpConfiguration config)
       at System.Web.Http.Cors.AttributeBasedPolicyProviderFactory.GetCorsPolicyProvider(HttpRequestMessage request)
  InnerException: 

      

If anyone could give me any advice on where I could help solve this problem, I would really appreciate it.

In particular, some can explain to me how the request is handled in this configuration. I find this quite confusing and I would like to know how WebAPI and Owin fit together. Without knowing this, I find it difficult to understand the problem.

Thank.

For reference: my WebAPI launch class:

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {

        // Configure the db context and user manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Configure the application for OAuth based flow
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };

        // Enable the application to use bearer tokens to authenticate users
        app.UseOAuthBearerTokens(OAuthOptions);

    }
}

      

Update 1 - the question is correct after Darin's comments. The problem is not with the constructor.

Update 2 - Removal Method:

    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            UserManager.Dispose();
        }

        base.Dispose(disposing);
    }

      

Update 3 - Added / Register method to show where I have a breakpoint (which was never reached)

+3


source to share


2 answers


There is no null validation for _userManager in your placement method, but the backing field can be null. Also you are accessing the UserManager property rather than using the background field directly. Therefore, every time _userManager is NULL and the AccountController user gains access, the UserManager will try to create a new OwinContext. And this will fail.

Change the placement method:



protected override void Dispose(bool disposing)
{
    if (disposing && _userManager != null)
    {
        _userManager.Dispose();
        _userManager = null
    }

    base.Dispose(disposing);
}

      

+3


source


I have a problem in the account constructor

The HTTP context is not available in the constructor of the controller, and that is by design. The earliest point of execution at which you can access it is after Initialize

:



protected override void Initialize(HttpControllerContext controllerContext)
{
    base.Initialize(controllerContext);

    // This is the earliest stage where you can access the HTTP context (request, response, ...).
}

      

+2


source







All Articles