从Web Api到Http请求从Mysql数据库中检索数据?

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

我试图从WebAPI应用程序中的MySQL数据库中检索一组数据,并通过移动应用程序的HTTP请求访问它。因此,我创建了一个WebApi,一个RestClient类和我将显示数据的类,这是我的代码。

Web 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)
    {
    }
}

因此,在我的数据库中,我有三行,电话号码为+233892929292,在过滤器后我必须得到三行。我也会过滤到主题和摘要列。

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类

    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()
         {

         }
    }

ModelDataClass中字符串的值设置在另一个类中,以便在MySQL数据库中发布。由于这不会导致问题,我没有包含代码。

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;
    }
   }

问题1如何从Mysql检索数据到通过REST客户端类访问的Web API(这是移动设备,所以我必须使用Http请求)?

问题2我想为通过MySQL数据库检索的每一行创建一个listView。标题是主题列中的数据,子标题是摘要列中的数据。

c# mysql asp.net-web-api xamarin.forms rest-client
2个回答
0
投票

您的应用程序采用Multitier Architecture模式设计。因此,您需要确保关注点分离。

Web API将代表您的表示逻辑层。它将解析客户端的请求,根据需要查询数据并根据需要格式化返回的数据。

然后,RetrieveClient可以处理数据访问层。它将根据需要管理对数据库的访问,插入,更新和删除。

这里的关键是确保每个层与另一个层交互以执行操作,并且不直接访问表示层中的数据库。

因此,

如何检索数据?

在您的数据访问层中:

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
}

以上将从数据库中获取记录,并将其作为对象返回。您可以使用ORM库,例如EntityFramework或NHibernate,但它们有自己的学习曲线。

如何返回数据?

您的客户端将调用Web API,Web API将从数据访问层查询数据。

[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
}

关于如何通过API访问数据,还有许多其他在线示例。看看谷歌和审查。一些浮现在脑海中的是

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


0
投票

我解决了这个问题。

的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)
{
}

}

Retrivedatatslass

   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;
    }


}

所以现在我得到一个listview,它包含数据库中的每一行,listview标题中的每个项目都是DisplayTopic,副标题是DisplayMain。

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