简体   繁体   English

从WebApi中的Mysql数据库中检索数据到HttpRecquest?

[英]Retrieve Data from Mysql Database in WebApi To HttpRecquest?

I am trying to retrieve a set of data from a MySQL database in a WebAPI application and access it through HTTP request from a mobile app. 我正在尝试从WebAPI应用程序中的MySQL数据库检索一组数据,并通过来自移动应用程序的HTTP请求来访问它。 Hence I created a WebApi, a RestClient class and the class where I would show the data, this is my code. 因此,我创建了一个WebApi,一个RestClient类以及用于显示数据的类,这就是我的代码。

Web API 网络API

[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
    // GET: api/Blog
    [HttpGet]
    public  IEnumerable<string>  Get()
    {

    }

    // GET: api/Blog/5
    [HttpGet("{id}", Name = "GetBlogItems")]
    public string Get(int id)
    {

    }

    // POST: api/Blog
    [HttpPost]
    public void Post([FromBody]  RetrieveDataClass value)
    {
        string sqlstring = "server=; port= ; user id =;Password=;Database=;";
        MySqlConnection conn = new MySqlConnection(sqlstring);
        try
        {
            conn.Open();
        }
        catch (MySqlException ex)
        {
            throw ex;
        }
        string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
        MySqlCommand cmd = new MySqlCommand(Query, conn);
        cmd.ExecuteReader();
        conn.Close();

    }

    // PUT: api/Blog/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE: api/ApiWithActions/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

So, in my database, I have three rows with a telephone number of +233892929292, after the filter I have to get three rows. 因此,在我的数据库中,我有三行,电话号码为+233892929292,在过滤器之后,我必须得到三行。 and I would also filter to only the topic and summary column. 并且我还将过滤到仅主题和摘要列。

RestClient Class RestClient类

   public class BlogRestClient<T>
{
    private const string WebServiceUrl = "http://localhost:57645/api/Blog/";

    public async Task<List<T>> GetAsync()
    {

        var httpClient = new HttpClient();

        var json = await httpClient.GetStringAsync(WebServiceUrl);

        var taskModels = JsonConvert.DeserializeObject<List<T>>(json);

        return taskModels;
    }


    public async Task<bool> PostAsync(T t)
    {

        var httpClient = new HttpClient();

        var json = JsonConvert.SerializeObject(t);

        HttpContent httpContent = new StringContent(json);

        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var result = await httpClient.PostAsync(WebServiceUrl, httpContent);

        return result.IsSuccessStatusCode;

    }

    public async Task<bool> PutAsync(int id, T t)
    {
        var httpClient = new HttpClient();

        var json = JsonConvert.SerializeObject(t);

        HttpContent httpContent = new StringContent(json);

        httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);

        return result.IsSuccessStatusCode;
    }

    public async Task<bool> DeleteAsync(int id, T t)
    {
        var httpClient = new HttpClient();

        var response = await httpClient.DeleteAsync(WebServiceUrl + id);

        return response.IsSuccessStatusCode;
    }
}

ModelData Class ModelData类别

    public class ModelDataClass
    {
         public string Telephone ;
         public string Created/Saved ;
         public string TopicSaved1 ;
         public string SummarySaved1 ;
         public string CategoriesSaved1 ;
         public string Body1 ;
         public string Body2 ;
         public string Body3 ;
         public string Body4 ;


         public ModelDataClass()
         {

         }
    }

The Values for the strings in ModelDataClass are set in another class to post in MySQL database. ModelDataClass中的字符串的值在另一个类中设置,以发布到MySQL数据库中。 Since that is not causing the problem in question, I have not included the code. 由于这不会引起问题,因此我没有包含代码。

RetrieveDataClass RetrieveDataClass

 public class RetrieveDataClass
    {
         public string Topic ;
         public string Summary ;

         public RetrieveDataClass()
         {
            GetDataEvent();
            AddBlog();
         }

          public void GetDataEvent()
         {
          BlogRestClient<ModelDataClass> restClient = new 
          BlogRestClient<ModelDataClass>();
            await restClient.GetAsync();
         }


      public ObservableCollection<ModelDataClass> BlogItems = new  
      ObservableCollection<ModelDataClass>();

    public void AddBlog()
    {
        BlogListView.ItemsSource = BlogItems;
    }
   }

Question1 How do I retrieve the data from, Mysql, to WebAPI accessed through the REST client class(It's for mobile so I have to use Http request)? Question1如何将数据从Mysql检索到通过REST客户端类访问的WebAPI(用于移动设备,因此必须使用Http请求)?

Question2 I would like to create a listView for each row I retrieve through the MySQL database. Question2我想为通过MySQL数据库检索的每一行创建一个listView。 With the heading being the data in the topic column and the subheading is with the data in summary column. 标题是主题列中的数据,子标题是摘要列中的数据。

Your application is designed with the Multitier Architecture pattern. 您的应用程序是使用“ 多层体系结构”模式设计的。 As such, you need to ensure you have a separation of concerns. 因此,您需要确保将关注点分开。

The Web API will represent your presentation logic layer. Web API将代表您的表示逻辑层。 It will parse the client's request, query for the data as required and format the returned data as needed. 它将解析客户端的请求,根据需要查询数据,并根据需要格式化返回的数据。

The RetrieveClient can then handle the data access layer. 然后,RetrieveClient可以处理数据访问层。 It will manage access to the database, insert, update, delete as needed. 它将管理对数据库的访问,根据需要插入,更新,删除。

The key point here is to ensure that each layer talks to the other to perform actions and that you do not directly access the database in your presentation layer. 这里的关键点是确保每一层都与另一层对话以执行操作,并且确保您不直接访问表示层中的数据库。

As such, 因此,

How to retrieve data? 如何获取数据?

In your Data Access Layer : 在您的数据访问层中:

public class RetrieveDataClass
{
    private IDbConnection connection;

    public RetrieveDataClass(System.Data.IDbConnection connection)
    {
        // Setup class variables
        this.connection = connection;
    }

    /// <summary>
    /// <para>Retrieves the given record from the database</para>
    /// </summary>
    /// <param name="id">The identifier for the record to retrieve</param>
    /// <returns></returns>
    public EventDataModel GetDataEvent(int id)
    {
        EventDataModel data = new EventDataModel();

        string sql = "SELECT id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4 WHERE id = @id";
        using (IDbCommand cmd = connection.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.CommandType = CommandType.Text;

            IDbDataParameter identity = cmd.CreateParameter();
            identity.ParameterName = "@id";
            identity.Value = id;
            identity.DbType = DbType.Int32; // TODO: Change to the matching type for id column

            cmd.Parameters.Add(identity);

            try
            {
                connection.Open();
                using (IDataReader reader = cmd.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        data.id = reader.GetInt32(reader.GetOrdinal("id"));
                        // TODO : assign the rest of the properties to the object
                    }
                    else
                    {
                        // TODO : if method should return null when data is not found
                        data = null;
                    }
                }
                // TODO : Catch db exceptions
            } finally
            {
                // Ensure connection is always closed
                if (connection.State != ConnectionState.Closed) connection.Close();
            }
        }

        // TODO : Decide if you should return null, or empty object if target cannot be found.
        return data;
    }

    // TODO : Insert, Update, Delete methods
}

The above will get a record from the database, and return it as an object. 上面的代码将从数据库中获取一条记录,并将其作为对象返回。 You can use ORM libraries such as EntityFramework or NHibernate instead but they have their own learning curve. 您可以改用诸如EntityFramework或NHibernate之类的ORM库,但是它们具有自己的学习曲线。

How to return the data? 如何返回数据?

Your client will call the WebAPI, which in turn query for the data from the data access layer. 您的客户端将调用WebAPI,后者依次从数据访问层中查询数据。

[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
    // TODO : Move the connection string to configuration
    string sqlstring = "server=; port= ; user id =;Password=;Database=;";

    // GET: api/Blog
    /// <summary>
    /// <para>Retrieves the given record from the database</para>
    /// </summary>
    /// <param name="id">Identifier for the required record</param>
    /// <returns>JSON object with the data for the requested object</returns>
    [HttpGet]
    public IEnumerable<string> Get(int id)
    {
        IDbConnection dbConnection = System.Data.Common.DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
        RetrieveDataClass dal = new RetrieveDataClass(dbConnection);

        EventDataModel data = dal.GetDataEvent(id);
        if (data != null)
        {
            // Using Newtonsoft library to convert the object to JSON data
            string output = Newtonsoft.Json.JsonConvert.SerializeObject(data);

            // TODO : Not sure if you need IEnumerable<string> as return type
            return new List<string>() { output };
        } else
        {
            // TODO : handle a record not found - usually raises a 404
        }
    }

    // TODO : other methods
}

There are lots of other examples online on how to access the data via API. 在线上还有许多其他示例,介绍如何通过API访问数据。 Have a look on google and review. 看看谷歌和审查。 A few that come to mind are 我想到的是

https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio

https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

i solved the problem. 我解决了这个问题。

WebApi 的WebAPI

[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// GET: api/Blog
[HttpGet]
 public List<BlogViews>  Get()
    {

            string sqlstring = "server=; port= ; user id =;Password=;Database=;";
            MySqlConnection conn = new MySqlConnection(sqlstring);
            try
            {
                conn.Open();
            }
            catch (MySqlException ex)
            {
                throw ex;
            }
            string Query = "SELECT * FROM test.blogtable where `Telephone` ='Created'";
            MySqlCommand cmd = new MySqlCommand(Query, conn);
            MySqlDataReader MSQLRD = cmd.ExecuteReader();
            List<BlogViews> GetBlogList = new List<BlogViews>();

            if (MSQLRD.HasRows)
            {

              while (MSQLRD.Read())
              {
                BlogViews BV = new BlogViews();
                BV.id = (MSQLRD["id"].ToString());
                BV.DisplayTopic = (MSQLRD["Topic"].ToString());
                BV.DisplayMain = (MSQLRD["Summary"].ToString());
                GetBlogList.Add(BV);
              }
            }
            conn.Close();
        return GetBlogList;
    }

// GET: api/Blog/5
[HttpGet("{id}", Name = "GetBlogItems")]
public string Get(int id)
{

}

// POST: api/Blog
[HttpPost]
public void Post([FromBody]  RetrieveDataClass value)
{
    string sqlstring = "server=; port= ; user id =;Password=;Database=;";
    MySqlConnection conn = new MySqlConnection(sqlstring);
    try
    {
        conn.Open();
    }
    catch (MySqlException ex)
    {
        throw ex;
    }
    string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
    MySqlCommand cmd = new MySqlCommand(Query, conn);
    cmd.ExecuteReader();
    conn.Close();

}

// PUT: api/Blog/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}

// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}

} }

RetriveDataClass RetriveDataClass

   public class RetrieveDataClass
   {

     public RetrieveDataClass()
     {
       AddBlog();
     }
  public class BlogViews
    {
        public string id { get; set; }
        public string DisplayTopic { get; set; }
        public string DisplayMain { get; set; }
        public ImageSource BlogImageSource { get; set; }
    }

    public List<BlogViews> BlogList1 = new List<BlogViews>();
    public async Task< List<BlogViews>> GetBlogs()
    {
        BlogRestClient<BlogViews> restClient = new BlogRestClient<BlogViews>();
        var BlogV = await restClient.GetAsync();
        return BlogV;
    }

    public async void AddBlog()
    {
        BlogList1 = await GetBlogs();
        BlogListView.ItemsSource = BlogList1;
    }


}

so now i get a listview ,which contains each row from the database and each item in the listview heading is DisplayTopic and subheading is DisplayMain. 所以现在我得到一个listview,它包含数据库中的每一行,并且listview标题中的每个项目都是DisplayTopic,子标题是DisplayMain。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM