已部署的ASP.Net Web API返回值未更新

问题描述 投票:0回答:2

我创建了一个Web API,它将从数据库中获取数据并以json格式返回。例如,我在我的数据库中有2条记录并调用web api它返回2条记录但是当我向数据库添加新数据时它没有显示结果。但是当我在本地运行它时显示3条记录。为了让我能够在我部署的api中看到3条记录,我需要重新进行重新安装和部署。有没有人有这样的经历?你是怎么解决这个问题的?

public class ContactRepository : IContactRepository
{
    private List<Contact> Contacts = new List<Contact>();
    private string ContactId;
    string connectionstring = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;

    public ContactRepository()
    {
        using (OleDbConnection conn = new OleDbConnection(connectionstring))
        {
            conn.Open();
            using (OleDbCommand cmd = new OleDbCommand("Select ContactId, Firstname, Lastname, Email, Mobile FROM sysdba.CONTACT WHERE LASTNAME LIKE 'R%' AND FIRSTNAME LIKE 'R%' AND EMAIL <> '' ORDER BY CreateDate DESC, LASTNAME, FIRSTNAME", conn))
            {
                OleDbDataReader dr;
                dr = cmd.ExecuteReader();
                while (dr.Read() == true)
                {
                    ContactId = dr[0].ToString();
                    Add(new Contact { Name = dr[1].ToString() + " " + dr[2].ToString(), Email = dr[3].ToString(), MobileNo = dr[4].ToString() });
                }
            }
        }
    }

    public IEnumerable<Contact> GetAll()
    {
        return Contacts;
    }
}

interface IContactRepository
{
    IEnumerable<Contact> GetAll();
    Contact Get(string id);
    Contact Add(Contact contact);
    void Remove(string id);
    bool Update(Contact contact);
}

public class ContactController : ApiController
{
    static readonly IContactRepository repository = new ContactRepository();

    public IEnumerable<Contact> GetAllContact()
    {
        return repository.GetAll();
    }
}
c# asp.net asp.net-web-api deployment
2个回答
1
投票

出现此问题的原因是您在Controller中创建了ContactRepository的静态实例。所以它只会创建一次。所以最终ContactRepository构造函数只会被调用一次。

我可以看到getAll()返回正在构造函数中填充的联系人列表。

为了让我能够在我部署的api中看到3条记录,我需要重新进行重新安装和部署。

问题出在静态实例上,因此无需重新部署。重新启动IIS也可以获得预期的结果。

因此,在构造函数中使ContactRepository非静态可以解决您的问题。

但是这会导致每次创建新实例时执行sql查询,所以更好的方法是将逻辑从构造函数移动到GetAll()中的ContactRepository方法。


0
投票

问题是你的ContactController有一个ContactRepository的静态成员,你唯一一次在数据库中查询联系人是在ContactRepository的构造函数内。

在第一次请求时,此静态初始化恰好发生一次,后续请求将始终返回相同的联系人列表。

您应该将您的成员更改为非静态成员,以便为每个控制器实例创建新的存储库实例,或者每次更改存储库GetAll方法以执行查询。

© www.soinside.com 2019 - 2024. All rights reserved.