ASP.NET MVC表单远程验证未通过异步api调用执行

时间:2019-02-05 22:04:33

标签: c# asp.net-mvc data-annotations unobtrusive-validation remote-validation

我在asp.net mvc表单上有电子邮件字段。我需要通过调用网络核心api服务器来使用远程验证来验证电子邮件。当电子邮件字段失去焦点时,将激活远程验证。但是,对api服务器的调用停在了对api方法的异步调用上。

    public class Model
    {
    [Required]
    [StringLength(50, ErrorMessage = "The {0} exceeds {1} characters")]
    [EmailAddress(ErrorMessage = "Invalid Email Address")] // NOTE:  This attribute REQUIRES .Net 4.5 or higher!
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email", ResourceType = typeof(Resources.Resources))]
    [Remote(action: "VerifyEmail", controller: "Account")]
    public string Email { get; set; }
    }

public class AccountController : Controller
{
    CoreApiHelp _apiHelper = new ApiHelp();
    public AccountController()
    {

    }
    [AllowAnonymous]
    [AcceptVerbs("Get", "Post")]
    public ActionResult VerifyEmail(string email)
    {
        if (!_apiHelper.VerifyEmail(email).Result)
        { 
            return Json($"Email {email} is already in use.");
        }

        return Json(true);
    }
   }
public class ApiHelp
{
    HttpClient _client = new HttpClient();
    SettingHelp _setting = new SettingHelp();
    IdentityServer4Help _serverHelp;
    const string IS_USER_EMAIL_UNIQUE = "User/IsEmailUnique?";
    public CoreApiHelp()
    {
        _serverHelp = new IdentityServer4Help(_setting.IdentityServer4Host, _setting.IdentityServer4ClientId,
            _setting.IdentityServer4ClientSecret, _setting.IdentityServer4ClientScope);
        _client.BaseAddress = new Uri(_setting.ApiHost);
    }
    public async Task<bool> VerifyEmail(string email)
    {
        var token = await _serverHelp.GetToken();
        _client.SetBearerToken(token);
        string uri = $"{IS_USER_EMAIL_UNIQUE}userEmail={email}";
        bool res = false;
        using (var response = await _client.GetAsync(uri))
        {
            await response.EnsureSuccessStatusCodeAsync();
            res = await response.Content.ReadAsAsync<bool>();
        }
        return res;
    }
   }

在执行VerifyEmail api调用之后,代码应返回true或false。但是,执行停在了“ await _serverHelp.GetToken();”行。如果在单击“提交”按钮后调用“ VerifyEmail”,则api调用可以正常工作。  调用异步方法进行远程验证似乎存在问题。远程验证示例中的方法是同步调用。

0 个答案:

没有答案