[.NET-Core- API ] - Web API 與前端參數繫結 搭配Postman測試筆記

  • 1112
  • 0
  • 2021-09-02

實務工作上遇到太多Get,Post搭配各式基底型別、class型別等等的Query API 串接,這次做個筆記避免之後又錯亂 XD

Step1.新增.Net Core MVC專案後建立 名為  MyTestAPI 的 控制器-空白 API Controller 為測試環境

Step2.將Controller最上方的宣告  [api/Route("[controller]")] → 改為簡易的[Route("[controller]")] 

Step3.建立Action開始實測

[Route("[controller]")]
[ApiController]
public class MyTestAPIController : BaseController
{
  public class TestClass
   {
      public long UserPK { get; set; }
      public string Name { get; set; }
    }
    
    public class AccounRole
    {
       public long UserType { get; set; }

        public long UserRole { get; set; }
     }

    public class UserViewData
    {
        public TestClass Test { get; set; }
        public List<AccounRole> AccountRoleList { get; set; }
    }
   
   //情境一
   [HttpGet("[action]")]
   public IActionResult GetData(int _ID)
   {
    var stop = "";
     return Content("OK ... You'r Input Data is ... " + _ID);
   }
    
    //情境二
    [HttpGet("[action]")]
    public IActionResult GetClassData([FromQuery]TestClass _test)
    {
       var stop = "";
       return Content("You'r Input Class 欄位有 ... " + _test.UserPK + " + " + _test.Name);
    }
    
    //情境三
    [HttpGet("[action]")]
    public IActionResult GetData2(int _ID, long _UserPK, string _Name)
    {
      var stop = "";
      return Content("You'r Input 搜尋條件有 ... " + _ID + " + " + _UserPK + " + " + _Name);
    }
    
    //情境四
    [HttpPost("[action]")]
    public IActionResult UpdateData([FromBody]TestClass _update)
    {
       var stop = "";
       return Content("You'r 更新欄位有 ... " + _update.UserPK + " + " + _update.Name);
    }
    
    //情境五
    [HttpPost("[action]")]
    public IActionResult UpdateDataList([FromBody] UserViewData _updateViewData)
    {
        string conetentString = "";
        if (_updateViewData.AccountRoleList!= null && _updateViewData.AccountRoleList.Count > 0)
        {
          foreach (var data in _updateViewData.AccountRoleList)
          {
              conetentString = conetentString +
              "data.UserType->" + data.UserType + "、" +
               "data.UserRole->" + data.UserRole + ",";
          }
            }
            return Content("You'r 更新的欄位有 ... " + _updateViewData.Test.UserPK + " + " + _updateViewData.Test.Name
                + "<br />更新的ViewData共有->" + conetentString);
        }
	}
	
        
        [HttpPost("[action]")]
        //情境六
        public IActionResult PostString([FromBody] string _postStr)
		{

			//略
		}
		
		//情境七
		[HttpPost("[action]")]
        public IActionResult PostFormData([FromForm] string _postForm)
        {
            //略
        }

//前端Get測試
$.ajax({
   method: "GET",
   url: '/MyTestAPI/GetData',
   cache: false,
   data: { _ID: 101, _UserPK: 5, _Name: 'NickZangTest' },
}).done(function (data) {
   //data為回傳結果與訊息
   console.log("result...", data);
});

1.實測 [HttpGet] 搭配任一個基底類型的API,只要網址後面有加入API對應參數並賦予值即可呼叫

 專案網址+/MyTestAPI/GetData?_ID=131


//$.ajax({
            //    method: "GET",
            //    url: '/MyTestAPI/GetClassData',
            //    cache: false,
            //    data: { UserPK: 100, Name: 'NickZ' },
            //}).done(function (data) {
            //    console.log("result...", data);
            //});

2. 實測 [HttpGet] 搭配指定的Class至API,後端繫結類別要用[FromQuery]  去包Model,前端將欄位名字+值並用&依序去串接即可

專案網址+ /MyTestAPI/GetClassData?UserPK=1&Name='Nick'


//$.ajax({
            //    method: "GET",
            //    url: '/MyTestAPI/GetData2',
            //    cache: false,
            //    data: { _ID: 101, _UserPK: 5, _Name: 'NickZangTest' },
            //}).done(function (data) {
            //    console.log("result...", data);
            //});

3.實測 [HttpGet] 搭配多個參數而不是用class傳到後端的話,可以不用[FromQuery] 

專案網址+ /MyTestAPI/GetData2?_ID=101&_UserPK=5&_Name=NickZangTest


var _data = { UserPK: 101, Name: 'NickZangTest...' };
 $.ajax({
     method: "Post",
     url: '/MyTestAPI/UpdateData',
     cache: false,
     data: JSON.stringify(_data),
     contentType: "application/json"
}).done(function (data) {
     console.log("result...", data);
});

4.實作[HttpPost] 搭配 class 更新或新增資料Post 這部分較不複雜只需前端資料包好丟到後端API網址即可,

後端action有沒有用[FromBody]都不影響,這邊要注意的是後端所接收的Model必填欄位是否都有值,如果沒有的話則會無法送出資料。


var _data = {
   Test: {
           UserPK: 1,
           Name: 'NickTest...',
          },
    AccountRoleList: [
           { UserType: 1, UserRole: 11 },
           { UserType: 2, UserRole: 22 },
           { UserType: 3, UserRole: 33 },
           ],
};

    $.ajax({
       method: "Post",
       url: '/MyTestAPI/UpdateDataList',
       cache: false,
       data: JSON.stringify(_data),
       contentType: "application/json"
       }).done(function (data) {
         console.log("result...", data);
       });

5.實作[HttpPost] 搭配 ViewModelClass 更新資料,實務上常常需要Post一包包含多Model及ListClass的情況,

 為此我們在前端先模擬送到後端的資料格式,單一Class對給予對應後端欄位名並給予傳送值,

    如果是List的資料用一樣給予後端欄位名,欄位值用 { }包好並用逗號區隔給個資料即可。 


var data = '這是測試...';
        $.ajax({
            method: "POST",
            url: '/MyTestAPI/PostString',
            cache: false,
            data: JSON.stringify(data),
            contentType: "application/json"
        }).done(function (data) {
});

6.實作[HttpPost] 搭配且只有一個基底欄位的情況,只需將值傳到後端即可不用在前面宣告命名


 var postData = new FormData();
        //前面是後端指定的欄位名稱
        //後面是值
        postData.append("_postForm", "這是TestA...");
        $.ajax({
            type: "POST",
            url: '/MyTestAPI/PostFormData',
            processData: false,
            contentType: false,
            data: postData
        }).done(function (data) {
        });
//也可以使用xhr方式回傳,xhr裡面一定要建立與回傳物件才會執行!

var postData = new FormData();
        //前面是後端指定的欄位名稱
        //後面是值
        postData.append("_postForm", "這是TestA...");
        
        var task = $.ajax({
            type: "POST",
             url: '/MyTestAPI/PostFormData',
            contentType: false,
            processData: false,
            cache: false,
            data: postData,
            xhr: function () {
            // 建立xhr(XMLHttpRequest)物件
                var xhr = new window.XMLHttpRequest(); 
                // 注意必須將xhr(XMLHttpRequest)物件回傳
                return xhr; 
            },
            success: function (response) {
            
            },
            error: function (XMLHttpRequest, response) {
            
            }
        });
        return task;

7.實作[HttpPost] 搭配前端new FormData(); 並將值依序append對應後端欄位名與值即可,兩個方法都可行用xhr 的話要建立xhr物件並在

functoin回傳才可以