使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

第一  创建ASP.NET Core Web API,选择C#语言。

选择图中的项目

使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

后面一路默认配置即可,创建后会有个实例代码,个人感觉挺有意义,对于初次使用的人很有参考价值。因为程序中用到图片转base64格式字符串和使用sqlserver数据库,需要下载NuGet程序包,下载方法,解决方案–右键–“管理解决方案的NuGet程序包”,下载如下缺少的包

 第二 连接数据库,并返回查询结果

1、首先创建一个类,保存web端返回的数据,比如我创建一个电视剧类,客户端查询电视剧时,返回电视剧列表。 

namespace MyWebServer

{

    // 电视剧列表使用

    public class Film

    {

        public string? film_name { get; set; }

        public string? film_type { get; set; }

        public string? film_desc { get; set; }

        // base64格式的图片

        public string? film_pic { get; set; }

        // 平均分

        public string? avg_score { get; set; }

        public string? film_video_url { get; set; }

        // 上架状态,待上架、已上架、已下架

        public string? film_status { get; set; }

        public string? film_up_time { get; set; }

        public string? film_down_time { get; set; }

        public string? create_time { get; set; }

        public string? update_time { get; set; }

        public string? create_oper { get; set; }

        public string? update_oper { get; set; }

 

    }

 使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

 

2、创建controller,提供给客户端查询使用。 

using Microsoft.AspNetCore.Mvc;

using Microsoft.Data.SqlClient;

using System.Data;

 

namespace MyWebServer.Controllers

{

    [ApiController]

    [Route(“[controller]”)]

    public class FilmListController : ControllerBase

    {

        private readonly ILogger _logger;

 

        public FilmListController(ILogger logger)

        {

            _logger = logger;

        }

        

        [HttpPost(Name = “GetFlimList”)]

        public IEnumerable GetFlimList()

        {

            List filmList = new List();

            try

            {

                // cinema_db2为数据库名,sa为数据库登录名,dbpassword为数据库密码。

                // 修改sa用户密码和设置以sql server身份登录方法见:https://blog.csdn.net/newdriverest/article/details/127120083

                // 修改完数据库sa密码后,记得重启数据库才能生效。

                SqlConnection sqlConnection = new SqlConnection(“Data Source=localhost;Initial Catalog=cinema_db2;Encrypt=True;Integrated Security=True;TrustServerCertificate=True;User Id=sa;Password=dbpassword”);

                sqlConnection.Open();

                // 语句可从sql server management sudio查询查询语句框中直接复制过来,去掉/r/n

                string sql = “SELECT [film_name],film_type,” +

                    “[film_desc],[film_pic_url],[film_video_url],film_status,” +

                    “[film_up_time],[film_down_time],[create_time],[update_time],” +

                    “[create_oper],[update_oper]” +

                    ” FROM [cinema_db2].[dbo].[t_film]”;

 

                DataSet dataSet = new DataSet();

                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection);

                sqlDataAdapter.Fill(dataSet);

 

                // 遍历结果

                if (dataSet.Tables.Count > 0)

                {

                    // 行

                    for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)

                    {

                        Film tmp = new Film();

                        // 列

                        for (int j = 0; j < dataSet.Tables[0].Columns.Count; j++)

                        {

                            if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_name”))

                            {

                                tmp.film_name = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            } else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_type”))

                            {

                                tmp.film_type = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            } else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_desc”))

                            {

                                tmp.film_desc = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_pic_url”))

                            {

                                tmp.film_pic = ImageToBase64(dataSet.Tables[0].Rows[i].ItemArray[j].ToString());

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_video_url”))

                            {

                                tmp.film_video_url = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_status”))

                            {

                                tmp.film_status = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_up_time”))

                            {

                                tmp.film_up_time = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“film_down_time”))

                            {

                                tmp.film_down_time = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“create_time”))

                            {

                                tmp.create_time = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“update_time”))

                            {

                                tmp.update_time = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“create_oper”))

                            {

                                tmp.create_oper = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                            else if (dataSet.Tables[0].Columns[j].ToString().Equals(“update_oper”))

                            {

                                tmp.update_oper = dataSet.Tables[0].Rows[i].ItemArray[j].ToString();

                            }

                        }

                        filmList.Add(tmp);

                    }

                }

 

                sqlConnection.Close();

                // 返回的数据,客户端使用相同的类字段接收即可,比如android端使用okhttp3+retrofit2+rxJava,很方便就能获取到返回的数据

                return filmList.ToArray();

            }

            catch (Exception ex)

            {

                Console.WriteLine(ex.Message);

                return filmList.ToArray();

            }

        }

        

        ///

        /// Image 转成 base64

        ///

        ///

        public static string ImageToBase64(string fileFullName)

        {

            try

            {

                if (fileFullName != null && !fileFullName.Equals(“”))

                {

                    Bitmap bmp = new Bitmap(fileFullName);

                    MemoryStream ms = new MemoryStream();

                    bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                    byte[] arr = new byte[ms.Length]; ms.Position = 0;

                    ms.Read(arr, 0, (int)ms.Length); ms.Close();

                    return Convert.ToBase64String(arr);

                }

                return “”;

            }

            catch (Exception ex)

            {

                return “”;

            }

        }

    }

使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

使用ASP.NET来创建与网站的连接可以通过以下步骤实现:

1. 首先,您需要在ASP.NET应用程序中创建一个数据库连接字符串,以便应用程序可以连接到数据库。您可以在Web.config文件中定义连接字符串,例如:

“`xml

 

“`

2. 然后,您可以在ASP.NET页面或代码中使用ADO.NET或Entity Framework等技术来连接到数据库并执行查询。例如,您可以使用SqlConnection和SqlCommand类来执行SQL查询,或者使用Entity Framework来执行LINQ查询。

“`csharp

string connectionString = ConfigurationManager.ConnectionStrings[“MyConnectionString”].ConnectionString;

using (SqlConnection connection = new SqlConnection(connectionString))

{

    string query = “SELECT * FROM MyTable”;

    using (SqlCommand command = new SqlCommand(query, connection))

    {

        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())

        {

            // 处理查询结果

        }

    }

}

“`

3. 最后,您可以将从数据库中检索到的数据绑定到网站上的控件,例如GridView、Repeater或DataList,以便在网站上显示数据。

通过这些步骤,您可以在ASP.NET应用程序中创建与网站的连接,并从数据库中检索数据以供网站使用。

4.链接数据库

要使用ASP.NET连接数据库,你可以按照以下步骤进行操作:

1. 首先,你需要在ASP.NET项目中添加一个数据库连接字符串,该字符串包含了连接到数据库的相关信息,例如数据库服务器的名称、数据库的名称、用户名和密码等。

2. 接下来,你可以使用ASP.NET提供的数据库连接对象(如SqlConnection)来建立与数据库的连接。你需要在代码中指定数据库连接字符串,并打开连接。

3. 一旦连接建立成功,你可以使用SQLCommand对象来执行数据库操作,例如查询、插入、更新或删除数据。

4. 最后,你需要在代码中关闭数据库连接,释放资源。

使用asp.net core web api创建web后台,并连接和使用Sql Server数据库和使用ASP.NET来创建与网站的连接

以下是一个简单的ASP.NET连接数据库的示例代码:

“`csharp

using System;

using System.Data;

using System.Data.SqlClient;

namespace YourNamespace

{

    public class YourClass

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            string connectionString = “Data Source=YourServerName;Initial Catalog=YourDatabaseName;User ID=YourUsername;Password=YourPassword”;

            using (SqlConnection connection = new SqlConnection(connectionString))

            {

                connection.Open();

                string sql = “SELECT * FROM YourTable”;

                using (SqlCommand command = new SqlCommand(sql, connection))

                {

                    using (SqlDataReader reader = command.ExecuteReader())

                    {

                        while (reader.Read())

                        {

                            // 读取数据库中的数据

                        }

                    }

                }

            }

        }

    }

}

“`

在上面的示例中,我们首先定义了一个数据库连接字符串,然后使用SqlConnection对象建立了与数据库的连接。接着,我们使用SqlCommand对象执行了一个简单的查询操作,并使用SqlDataReader对象读取了查询结果。

当然,实际的数据库操作可能更加复杂,例如参数化查询、事务处理等,你可以根据具体的需求来扩展和修改上面的示例代码。

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://www.net2asp.com/8bc6949f65.html