Api開發教程「api教程完整版pdf」

一、準備工作

1.Visual Studio NuGet程序包源配置

源地址:
http://47.102.150.59:8087/nuget/

一些輔助功能包,能提高開發效率

.Net Core Web Api開發教程 Part 1

2.創建項目

選擇項目類型、自定義項目名稱

.Net Core Web Api開發教程 Part 1

3.基礎配置

項目應用端口配置、IOC容器配置、日誌配置、數據庫配置、Map映射配置…

 //Program.cs
         public static void Main(string[] args)
         {
             var config = new ConfigurationBuilder()
                 .SetBasePath(Directory.GetCurrentDirectory())
                 // 添加端口配置文件
                 .AddJsonFile("hosting.json", true)
                 .Build();
 
             var host = Host.CreateDefaultBuilder(args)
                 // 添加Autofac作為IOC容器
                 .UseServiceProviderFactory(AppServiceProvider.Instance().AutofacServiceProviderFactory)
                 .ConfigureWebHostDefaults(webHostBuilder =>
                 {
                     webHostBuilder
                       .UseContentRoot(Directory.GetCurrentDirectory())
                       .UseConfiguration(config)
                       .UseStartup<Startup>();
                 })
                 .Build();
 
             host.Run();
         }
 //Startup.cs
         public void ConfigureServices(IServiceCollection services)
         {
             MapperHelper.CreateMap();//Map映射配置
             services.UseNCoreAspNet<NCoreAspNetOptions>(options =>
             {
                 //日誌配置
                 options.Log4netConfig = "log4net.config";
                 options.UseUpload = true;
                 options.UseAnyCors = true;
                 options.ApiSecurityFilter = false;
                 //數據庫配置
                 options.DefaultDBOptions = new DefaultDBOptions
                 {
                     DBSectionName = "DBConnectionSetting",
                     DefaultConnectionName = "defaultConnection"
                 };
             });
         }

二、API實現

1.創建數據模型(ViewModel)

定義接口需要數據屬性(名稱、類型、約束等…)【屬性命名規則全部用小寫,方便前端 JS 調用時不用檢查某個屬性大小寫問題】

     /// <summary>
     ///用戶基本信息
     /// </summary>
     public class UserViewMmodel
     {
         /// <summary>
         /// 用戶名
         /// </summary>
         public string user_name { get; set; } = "hanbing";
 
         /// <summary>
         /// 昵稱
         /// </summary>
         public string nickname { get; set; } = "老盧聊技術";
 
         /// <summary>
         /// qq號碼
         /// </summary>
         public string qq { get; set; } = "81868164";
 
         /// <summary>
         ///微信號碼
         /// </summary>
         public string wxid { get; set; } = "hanbing_81868164";
 
         /// <summary>
         /// 地址
         /// </summary>
         public string address { get; set; }
 
         /// <summary>
         /// 年齡
         /// </summary>
         public int age { get; set; }
 
         /// <summary>
         /// 創建時間
         /// </summary>
         public DateTime creation_time { get; set; }
 
         /// <summary>
         /// 版本信息
         /// </summary>
         public string version { get; set; }
     }

2.創建控制器(Controller),編寫邏輯代碼

1).設置接口輸出數據格式(JSON或XML)

     [Produces("application/json")]//Controller中方法默認輸出json格式數據
     //[Produces("application/xml")]//Controller中方法默認輸出xml格式數據
     public class TestApiController : Controller

2).設置接口路由(定義接口版本【方便後期和新版本區分】)

     [Route("api/v1/testapi")]//固定路由配置
     //[Route("api/v1/[controller]")]//固定部分路由配置
     public class TestApiController  : Controller

3).設置接口請求Method,常見如下:

GET :從服務器取出資源(一項或多項)

POST :在服務器新建一個資源

PUT :在服務器更新資源(客戶端提供改變後的完整資源)

PATCH :在服務器更新資源(客戶端提供改變的屬性)

DELETE :從服務器刪除資源

         /// <summary>
         /// 返回用戶信息接口
         /// </summary>
         /// <returns></returns>
         [HttpGet]//請求方法為GET
         [Route("getuser")]//自定義路由
         //[Produces("application/xml")]//輸出xml格式
         public Task<UserViewMmodel> Index()
         {}

4).返回JSON數據格式接口

         /// <summary>
         /// 返回用戶信息接口
         /// </summary>
         /// <returns></returns>
         [HttpGet]//請求方法為GET
         [Route("getuser")]//自定義路由
         //[Produces("application/xml")]//輸出xml格式
         public Task<UserViewMmodel> Index()
         {
             return Task.Run(() =>
             {
                 UserViewMmodel res = null;
                 //業務邏輯代碼....
                 res = new UserViewMmodel
                 {
                     address = "上海市浦東區世紀大道200號",
                     age = 23,
                     creation_time = DateTime.Now,
                     version = "v1.0"
                 };
 
                 return res;
             });
         }

5).返迴文件(輸出文件)接口

         /// <summary>
         /// 輸出文件接口
         /// </summary>
         /// <returns></returns>
         [HttpGet]//請求方法為GET
         [Route("getfile")]//自定義路由
         public FileResult Download()
         {
             var fileData = $"{Directory.GetCurrentDirectory()}/wwwroot/css/site.css";
             var actionresult = new FileStreamResult(fileData.GetFileData().ToStream(), "text/css");
             actionresult.FileDownloadName = "site.css";
             return actionresult;
         }

6).裁剪圖片接口

         /// <summary>
         /// 裁剪圖片接口
         /// </summary>
         /// <param name="width"></param>
         /// <param name="name"></param>
         /// <returns></returns>
         [HttpGet]//請求方法為GET
         [Route("getimage/{width}/{name}")]//自定義路由
         public IActionResult GetImage(int width, string name)
         {
             var imgPath = $@"{Directory.GetCurrentDirectory()}/wwwroot/imgs/{name}";
 
             //縮小圖片
             using (var imgBmp = new Bitmap(imgPath))
             {
                 //找到新尺寸
                 var oWidth = imgBmp.Width;
                 var oHeight = imgBmp.Height;
                 var height = oHeight;
                 if (width > oWidth)
                 {
                     width = oWidth;
                 }
                 else
                 {
                     height = width * oHeight / oWidth;
                 }
                 var newImg = new Bitmap(imgBmp, width, height);
                 newImg.SetResolution(72, 72);
                 byte[] bytes;
                 using (var ms = new MemoryStream())
                 {
                     newImg.Save(ms, ImageFormat.Bmp);
                     bytes = ms.GetBuffer();
                 }
                 return new FileContentResult(bytes, "image/jpeg");
             }
         }

7).上傳單個文件接口

         /// <summary>
         /// 上傳文件,需要指定name值為fromFile,如:form-data; name="fromFile"; filename="8.png"
         /// </summary>
         /// <param name="fromFile"></param>
         /// <returns></returns>
         [Route("upfile")]//自定義路由
         [HttpPost]//請求方法為POST
         [AllowAnonymous]
         public UpFileViewModel UplodeFile([FromForm] IFormFile fromFile)
         {
             if (fromFile != null)
             {
                 using (var sm = fromFile.OpenReadStream())
                 {
                     string savePath = $"{Directory.GetCurrentDirectory()}/wwwroot/temp/{Id.LongId()}{fromFile.FileName.GetExtension()}";
                     sm.Save(savePath);
                 }
                 return new UpFileViewModel { code = 0, msg = "保存成功" };
             }
             return new UpFileViewModel { code = 1, msg = "保存失敗" };
         }

8).上傳多個文件接口

         /// <summary>
         /// 上傳多個文件,需要指定name值為files,如:form-data; name="files"; filename="8.png"
         /// </summary>
         /// <param name="fromFile"></param>
         /// <returns></returns>
         [Route("upfiles")]//自定義路由
         [HttpPost]//請求方法為POST
         [AllowAnonymous]
         public UpFileViewModel UplodeFiles([FromForm] IFormFileCollection files)
         {
             if (files != null)
             {
                 files.ForEach(fromFile =>
                 {
                     using (var sm = fromFile.OpenReadStream())
                     {
                         string savePath = $"{Directory.GetCurrentDirectory()}/wwwroot/temp/{Id.LongId()}{fromFile.FileName.GetExtension()}";
                         sm.Save(savePath);
                     }
                 });
                 return new UpFileViewModel { code = 0, msg = "保存成功" };
             }
             return new UpFileViewModel { code = 1, msg = "保存失敗" };
         }

9).上傳多文件接口,上傳時不需要指定name參數

         /// <summary>
         /// 上傳時不需要指定name參數:form-data; name=""; filename="222222222222.jpg"
         /// </summary>
         /// <returns></returns>
         [Route("upfiles2")]//自定義路由
         [HttpPost]//請求方法為POST
         [AllowAnonymous]
         public UpFileViewModel UplodeFiles2()
         {
             var files = this.Request.Form?.Files;
             if (files != null)
             {
                 files.ForEach(fromFile =>
                 {
                     using (var sm = fromFile.OpenReadStream())
                     {
                         string savePath = $"{Directory.GetCurrentDirectory()}/wwwroot/temp/{Id.LongId()}{fromFile.FileName.GetExtension()}";
                         sm.Save(savePath);
                     }
                 });
                 return new UpFileViewModel { code = 0, msg = "保存成功" };
             }
             return new UpFileViewModel { code = 1, msg = "保存失敗" };
         }

4).待續…

3.進行接口調用測試

4.增加日誌記錄功能

5.發佈接口程序到服務器(windows & linux)

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/268824.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-16 13:11
下一篇 2024-12-16 13:11

相關推薦

發表回復

登錄後才能評論