1. 程式人生 > 其它 >.Net Core 5下WebAPI FromForm 及FromBody FromQuery使用方式,有圖有真相

.Net Core 5下WebAPI FromForm 及FromBody FromQuery使用方式,有圖有真相

https://blog.csdn.net/hamunet/article/details/120968882

  1. FromForm POST方式
    後端程式碼:
    [HttpPost("Tel/FromFormTest")]
    public async Task<ActionResult<ResponseMessageWrap>> FromFormTest([FromForm] TelOutPos telOutPos)
    {
    await Task.CompletedTask;
    return new ResponseMessageWrap {Data= telOutPos.agNo };
    }

Js請求:
1、 Content-Type:application/x-www-form-urlencoded
var settings = {
"url": "http://localhost:5003/Tel/FromFormTest",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/x-www-form-urlencoded"
},
"data": {
"regId": "123131",
"token": "123123",
"agNo": "123213",
"bindTel": "2222"
}
};

$.ajax(settings).done(function (response) {
console.log(response);
});

2、 Content-Type:multipart/form-data
var form = new FormData();
form.append("regId", "11");
form.append("token", "22");

var settings = {
"url": "http://localhost:5003/Tel/FromFormTest",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};

$.ajax(settings).done(function (response) {
console.log(response);
});

3、Content-Type:application/json 物件值傳不過去

總結:
1、介面引數為物件:只能key value方式物件傳遞,後臺可以接收到,符合以上3中方式
2、介面引數分別接受,url方式傳值不考慮Content-Type 型別都可以接受到的
...FromFormTest1?regId=13&token=1213&agNo=123213&bindTel=123123

後臺程式碼 Dictionary 為key value 集合:
public static async Task<(bool, string)> HttpPostAsyncOptimizeFormUrl(string requestUrl, Dictionary<string, string> dicUrl)
{
try
{
using (HttpClient httpClient = new HttpClient())
{
StringBuilder builder = new StringBuilder();
int i = 0;
foreach (var item in dicUrl)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
var responseResult = httpClient.PostAsync(requestUrl, new StringContent(builder.ToString(), System.Text.Encoding.UTF8, "application/x-www-form-urlencoded")).Result;
if (responseResult.StatusCode == HttpStatusCode.OK)
{
return (true, await responseResult.Content.ReadAsStringAsync());
}
else
{
return (false, $"介面地址返回錯誤狀態碼:{responseResult.StatusCode}");
}

            }
        }

2.FromBody POST方式
後臺程式碼:
[HttpPost("Tel/FromBodyTest")]
public async Task<ActionResult<ResponseMessageWrap>> FromBodyTest([FromBody] TelOutPos telOutPoso)
{
await Task.CompletedTask;
return new ResponseMessageWrap { Data = telOutPoso.agNo };
}
JS:
var settings = {
"url": "http://localhost:5003/Tel/FromBodyTest",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"agNo": "1123"
}),
};

$.ajax(settings).done(function (response) {
console.log(response);
});
只能才作用 "Content-Type": "application/json" 這種方式 ,其他方式一律報media type 錯誤

3.FromQuery
介面引數物件可以接受URL傳值,不接受物件傳值,GET方式比較符合這種場景,POST當然也可以
FromQueryTest?egId=13&token=1213&agNo=123213&bindTel=123123
後臺程式碼:
[HttpPost("Tel/FromQueryTest")]
public async Task<ActionResult<ResponseMessageWrap>> FromQueryTest([FromQuery] TelOutPos telOutPos)
{
await Task.CompletedTask;
return new ResponseMessageWrap { Data = telOutPos.agNo };
}