ASP.NET MVC 5 API应用程序使用其自己的连接字符串而不是引用的应用程序连接字符串

时间:2018-08-01 12:58:13

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

我有一个包含2个应用程序的解决方案

  • 应用程序(.NET应用程序)
  • ApiApplication(控制台应用程序)

在应用程序中,我有以下控制器:

public class ApiAccountController : Controller
{
    ApplicationDbContext dbContext = new ApplicationDbContext();
    Logger log = LogManager.GetCurrentClassLogger();
    PasswordHasher passwordHasher = new PasswordHasher();

    // GET: Account
    public bool AuthenticateUser(String username, String password)
    {
        try
        {
            var user = dbContext.Users.FirstOrDefault(u => u.UserName == username);
            //var user = dbContext.Users.Count(u => u.UserName == username);
            if (user == null)
            {
                log.Error(username + " not found");
                return false;
            }
            else
            {
                var result = passwordHasher.VerifyHashedPassword(user.PasswordHash, password);
                if (result == PasswordVerificationResult.Success)
                {
                    return true;
                }
                else
                {
                    log.Error("Invalid password for user: " + username);
                    return false;
                }
            }
            //return false;
        }
        catch (Exception e)
        {
            log.Error(e, "Exception found for user: " + username);
            return false;
        }
    }
}

在ApiApplication中,我有这个Api类:

public class TokenController : ApiController
{
    // This is naive endpoint for demo, it should use Basic authentication to provide token or POST request
    // GET api/token/
    public string Get(string username, string password)
    {
        if (CheckUser(username, password))
        {
            return JwtManager.GenerateToken(username);
        }
        throw new HttpResponseException(HttpStatusCode.Unauthorized);
    }

    private bool CheckUser(string username, string password)
    {
        ApiAccountController accountController = new ApiAccountController();
        return accountController.AuthenticateUser(username,password);
    }
}

ApiApplication引用了Application,我想从Application调用AuthenticateUser。以前,当我尝试运行它时,AuthenticateUser总是返回null,我设法将其范围缩小到与dbContext有关的范围。但是,我发现,当我将Application的连接字符串放入ApiApplication时,出现一个错误,提示我的数据库已经存在。

ApiApplication的目的仅是接收请求并将其传递给Application并从ApiApplication检索数据。它根本不应该连接到数据库。我想念什么吗?当ApiApplication调用AuthenticateUser方法时,我应该为Application指定connectionString吗?

0 个答案:

没有答案