使用asp.net core web api创建web后台,并连接和使用Sql Server数据库

前言:因为要写一个安卓端app,实现从服务器中获取电影数据,所以需要搭建服务端代码,之前学过C#,所以想用C#实现服务器段代码用于测试,本文使用C#语言,使用asp.net core web api组件搭建服务器端,并访问sql server 数据库。

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

如下图所示

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

2.安装Nuet程序包——项目——依赖项——管理NuGet程序包(版本等级尽量一样)

Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer (适用于EF Core SQL Server 提供程序)
Microsoft.EntityFrameworkCore.Tools(适用于 EF Core 的包管理器控制台工具)

Microsoft.EntityFrameworkCore.Design(适用于EF Core .NET Core CLI 工具 )

system.Drawing.Common
Newtonsoft.Json
swashbuckle.AspNetCore

三、连接数据库,并返回查询结果

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

namespace MyWebServer.Model
{
    // 电影列表使用
    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.Http;
using Microsoft.AspNetCore.Mvc;

using Microsoft.Data.SqlClient;
using MyWebServer.Model;
using System.Data;
using System.Drawing;

namespace MyWebServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    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 "";
            }
        }





    }
}

运行程序之后,会打开调试用的web页面和一个命令行窗口,在浏览器测试页面,可以测试服务器接口的可用性,点击如下图的Try it out按钮,再点击Execute按钮,即可测试接口的返回结果。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值