我的 Xamarin.Forms 移动应用程序使用 Web Api 和 Asp.Net 标识来注册用户并将信息存储在名为 dbo.AspNetUsers 的默认 Azure 表中。我想在注册用户之前检查记录是否存在,如果用户已经存在,则返回相关消息(在这种情况下,电子邮件应该是唯一的)。
在我的 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();
}
在我的 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;
}
粗略地看一下UserManager的文档,可以看到 FindByNameAsync方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句