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

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

选择图中的项目

后面一路默认配置即可,创建后会有个实例代码,个人感觉挺有意义,对于初次使用的人很有参考价值。因为程序中用到图片转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; }
 
    }

 

 

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<FilmListController> _logger;
 
        public FilmListController(ILogger<FilmListController> logger)
        {
            _logger = logger;
        }
        
        [HttpPost(Name = "GetFlimList")]
        public IEnumerable<Film> GetFlimList()
        {
            List<Film> filmList = new List<Film>();
            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();
            }
        }
        
        /// <summary>
        /// Image 转成 base64
        /// </summary>
        /// <param name="fileFullName"></param>
        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来创建与网站的连接可以通过以下步骤实现:

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

```xml
<connectionStrings>
  <add name="MyConnectionString" connectionString="Data Source=YourServer;Initial Catalog=YourDatabase;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
```

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连接数据库的示例代码:

```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对象读取了查询结果。

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

  • 39
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值