无法检查用户名是否存在

时间:2016-10-25 00:28:03

标签: c# asp.net-core asp.net-identity asp.net-core-mvc

我是Stackoverflow的新手,我刚开始使用.NET Core并且第一次使用身份。我基本上是使用ajax调用控制器来查看用户名是否已经存在。然后我做了一些研究,发现我可以使用下面的RemoteAttribute是我的RegisterViewModel。

    public class RegisterViewModel
{
    [Required]
    [StringLength(100, ErrorMessage = "some error", MinimumLength = 2)]
    [DataType(DataType.Text)]
    [Display(Name = "Username")]
    [RegularExpression(@"(^[\w]+$)", ErrorMessage = "some error")]
    [Remote("CheckUserName", "Account", HttpMethod = "POST", ErrorMessage = "some error")]
    public string Username { get; set; }

然后在我的控制器中我有这个。

    public async Task<JsonResult> CheckUserName(string username)
    {
        var user = db.Users.Where(x => x.UserName == username).FirstOrDefault();
        if (user == null)
            return Json(true);
        else
            return Json(false);    
    }

但我的datacontext总是抛出对象引用没有设置为对象的实例,所以我使用了 FindByNameAsync Identity方法,它总是返回null,见下文。

    public async Task<JsonResult> CheckUserName(string username)
    {
        var user = await _userManager.FindByNameAsync(username);
        //but user is always null ??
    }

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

我不知道我做了什么,但它现在似乎在起作用。 我添加了

#include <iostream>
#include <fstream>
#include <cstdlib>

int main()
{
  // make sure that system("pause") is called on all exit paths
  struct cleanup
  {
    ~cleanup() { std::system("pause"); }
  } do_cleanup;

  // get the file name
  std::string filename;
  std::cout << "Enter the name of the file you would like to open: ";
  std::getline(std::cin,filename);
  if (!std::cin)
  {
    std::cerr << "Failed to read the file name.\n";
    return EXIT_FAILURE;
  }

  // open the file
  std::ifstream infile(filename.c_str());
  if (!infile)
  {
    std::cerr << "Could not open file: " << filename << "\n";
    return EXIT_FAILURE;
  }

  // print the file
  std::cout << infile.rdbuf();

  // close the file
  infile.close();
  if (!infile)
  {
    std::cerr << "Could not properly close file: " << filename << "\n";
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}
方法之上的

属性可能已经完成了。但那不是它应该抛出一个401错误。无论哪种方式,谢谢大家的帮助。