0

私はAsp.net mvc Webアプリケーションを開発中です。私のアプリケーションでは、カスタムのリモート検証属性を実装する必要があります。私はそれをうまく実装することができます。しかし、遠隔検証方法であるコントローラアクションメソッドのアイデンティティシステムのユーザには問題があります。アイデンティティシステムASP.NET MVCのカスタムリモート検証属性のアクションメソッドで常にユーザーはnullです

これは、あなたが上記の見ることができるように私は私の名前がユニークかそうでないチェックしています、この

public class UpdateAccountModel 
{ 
    [Required] 
    [RemoteClientServer("IsNameUnique", "Account" , ErrorMessage = "Username is already taken")] 
    public string UserName { get; set; } 
    [Required] 
    [EmailAddress] 
    [RemoteClientServer("IsEmailUnique", "Account" , ErrorMessage = "Email is already taken")] 
    public string Email { get; set; } 
} 

のようなビューモデルクラスを持っている想像してみましょう私の完全なリモート検証属性クラス

public class RemoteClientServerAttribute : RemoteAttribute 
{ 
    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     // Get the controller using reflection 
     Type controller = Assembly.GetExecutingAssembly().GetTypes() 
      .FirstOrDefault(type => type.Name.ToLower() == string.Format("{0}Controller", 
       this.RouteData["controller"].ToString()).ToLower()); 
     if (controller != null) 
     { 
      // Get the action method that has validation logic 
      MethodInfo action = controller.GetMethods() 
       .FirstOrDefault(method => method.Name.ToLower() == 
        this.RouteData["action"].ToString().ToLower()); 
      if (action != null) 
      { 
       // Create an instance of the controller class 
       //object instance = Activator.CreateInstance(controller); 
       object instance = DependencyResolver.Current.GetService(controller); 
       // Invoke the action method that has validation logic 
       object response = action.Invoke(instance, new object[] { value }); 
       if (response is JsonResult) 
       { 
        object jsonData = ((JsonResult)response).Data; 
        if (jsonData is bool) 
        { 
         return (bool)jsonData ? ValidationResult.Success : 
          new ValidationResult(this.ErrorMessage); 
        } 
       } 
      } 
     } 

     return ValidationResult.Success; 
     // If you want the validation to fail, create an instance of ValidationResult 
     // return new ValidationResult(base.ErrorMessageString); 
    } 

    public RemoteClientServerAttribute(string routeName) 
     : base(routeName) 
    { 
    } 

    public RemoteClientServerAttribute(string action, string controller) 
     : base(action, controller) 
    { 
    } 

    public RemoteClientServerAttribute(string action, string controller, 
     string areaName) 
     : base(action, controller, areaName) 
    { 
    } 
} 

です。電子メールアドレス用。これをユーザープロファイルを更新するためのビューモデルと見なします。ユーザーは現在ログインしています。名前が一意であることを確認するため、現在ログに記録されているユーザー値を削除するかどうか確認します。たとえば、現在記録されているメールは「[email protected]」です。ユーザーが電子メールのために同じ電子メールを入力した場合、検証は合格となります。しかし、電子メールが別のアカウントで存在する場合、検証は失敗します。

この

は削除検証アクションメソッドに見ることができるように一意の電子メール

public JsonResult IsEmailUnique(string Email) 
{ 
    bool isUnique = false; 
    if(!string.IsNullOrEmpty(Email)) 
    { 
     string userId = User.Identity.GetUserId();//Error throws here because User is null 
     isUnique = _userRepo.Users.Any(x => x.Email.Trim() == Email.Trim() && x.Id != userId) == false; 
    } 
    return Json(isUnique, JsonRequestBehavior.AllowGet); 
} 

をチェックするための削除検証アクションメソッドですが、私は現在ログインしているユーザーの取得しています。しかし、それはnullを返します。なぜ私は考えていない。しかし、私は他のアクションメソッドで取得することができます。たとえば、プロファイルの編集アクションです。私はこのように取得することができます。

public ActionResult EditAccount() 
{ 
    var name = User.Identity.GetUserName();// This is working fine when I directly access from url. 
    //do other stuffs 
} 

なぜ、無効な検証属性のアクションメソッドでAsp.netアイデンティティシステムのユーザーが常にnullになるのですか?私はパラメータとしてUserIdを渡したくありません。ユーザーは非常に簡単に変更することができます。私はちょうどそれを内部的に取り戻したい。

答えて

0

は、コントローラのアクションメソッドでHttpContext.Current.User.Identity.GetUserIdを呼び出すことはできませんHttpContext.Current.User.Identity.GetUserId();代わりのUser.Identity.GetUserId();

+0

試してみてください。私はControllerContext.HttpContext.User.Identity.GetUserId()を呼び出しました。代わりに。私はHttpContext.User.Identity.GetUserId()を呼び出しました。同じように。私が知ったのはコントローラーコンテキストもnullです。どちらもヌル例外をスローします。 –