Search code examples
azureasp.net-web-apixamarin.formsasp.net-identity

How to check if record exists in Azure table with Asp.Net Identity and return a custom response


My Xamarin.Forms mobile app uses a Web Api and Asp.Net Identity to register the user and store the information in a default Azure table called dbo.AspNetUsers. I would like to check whether the record exists before registering the user and return a relevant message if the user already exists (email should be unique in this case).

In my Web Api:

    [Route("Register")]
    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var user = new ApplicationUser() { UserName = model.Email, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Region = model.Region };

        IdentityResult result = await UserManager.CreateAsync(user, model.Password);

        if (!result.Succeeded)
        {
            return GetErrorResult(result);
        }

        return Ok();
    }

In my Xamarin.Forms PCL:

public class RegisterBindingModel
{
    public string Email { get; set; }

    public string Region { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Password { get; set; }

    public string ConfirmPassword { get; set; }

}

public async Task<bool> RegisterAsync (string email, string password, string confirmPassword, string firstName, string lastName, string region)
    {
        var client = new HttpClient();

        // create object to send to web api for registering
        var model = new RegisterBindingModel
        {
            Email = email,
            Password = password,
            ConfirmPassword = confirmPassword,
            FirstName = firstName,
            LastName = lastName,
            Region = region
        };

        var json = JsonConvert.SerializeObject(model);

        HttpContent content = new StringContent(json);

        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        // add for API Key
        content.Headers.Add(AppConstants.API_KEY_NAME, AppConstants.API_KEY_VALUE);

        var response = await client.PostAsync(AppConstants.AZURE_WEB_API_REGISTER_URL, content);

        return response.IsSuccessStatusCode;
    }

Solution

  • a cursory glance at the docs for UserManager shows a FindByNameAsync method