axios Post請求 .Net Core中的接口以及FromBody特性和FromForm特性的使用

.Net Core中Get請求接口的參數通常能夠在url中獲取,可是Post請求接口通常建議使用[FromBody]特性來綁定參數,而前端發請求時也得須要注意,前端代碼以下(vue):前端

const postData = {
    id: 12
}; // post請求的數據,可自行定義
this.$axios({
    url: api.postUrl,
    method: 'post',
    params: postData  
}).then((result) => {
    this.$message({
        message: '請求成功',
        type: 'success',
        showClose: true
    });
}).catch((err) => {
    this.$message({
        message: '請求失敗',
        type: 'error',
        showClose: true
    });
})
複製代碼

後端代碼以下(.Net Core):vue

[HttpPost]
public ActionResult HandlePost(int id) {
    return Content(id);
}
複製代碼

FromBody特性的使用

若是使用上述方法請求,會發現id能夠正常獲取,由於axios以params方式提交post參數時,默認將參數放在url後面,然後端接口的參數中若是不加其餘參數驗證的註解,則會默認從url中尋找參數。而若是在接口的參數驗證中加[FromBody]註解時,因爲[FromBody]註解沒法綁定簡單類型的參數,所以將參數的類型改爲dynamic,其中dynamic類型爲動態類型,和Object類型相似,因此須要使用obj. id的方式來獲取參數,即代碼以下:ios

[HttpPost]
public ActionResult HandlePost([FromBody] dynamic obj) {
    return Content(obj.id);
}
複製代碼

再次請求會發現後端報錯415 UnSupported Media Type,由於當以params方式提交post參數時,請求頭中無Content-Type字段,Axios源碼中對請求作了處理,以下圖: json

由此可知當使用params方式提交post參數時,即data參數爲空時,即便手動設置請求頭的Content-Type也會被清除,因此後端代碼因爲沒法識別Content-Type字段,致使報錯415 UnSupported Media Type。 爲了解決這個問題,則能夠將post提交參數的方式改爲data方式提交,代碼以下:

const postData = {
    id: 12
}; // post請求的數據,可自行定義
this.$axios({
    url: api.postUrl,
    method: 'post',
    data: postData  
}).then((result) => {
    this.$message({
        message: '請求成功',
        type: 'success',
        showClose: true
    });
}).catch((err) => {
    this.$message({
        message: '請求失敗',
        type: 'error',
        showClose: true
    });
})
複製代碼

而後再次請求會發現成功返回傳的id參數值。axios

這裏須要注意的是FromBody特性只接受Content-Type爲application/json的請求,只有這樣參數才能正確綁定,而axios的post請求中Content-Type默認爲application/json, 若是在上述前端代碼中手動修改請求頭爲application/x-www-formencoded或者multipart/form-data,則後臺接口又會報錯415 UnSupported Media Type. 後端

FromForm特性的使用

FromForm特性和FromBody特性的區別是:FromForm特性是用來綁定form-data格式中的表單數據,即Content-Type爲multipart/form-data,因此前端代碼應修改成以下:api

let formData = new FormData();
formData.append('id', 1212);
this.$axios({
    url: api.postUrl,
    method: 'post',
    // 手動設置Content-Type爲form-data格式
    headers: {
      'Content-Type': 'multipart/form-data'  
    },
    data: formData  
}).then((result) => {
    this.$message({
        message: '請求成功',
        type: 'success',
        showClose: true
    });
}).catch((err) => {
    this.$message({
        message: '請求失敗',
        type: 'error',
        showClose: true
    });
})
複製代碼

後端代碼修改成以下bash

[HttpPost]
public ActionResult HandlePost([FromForm] int id) {
    return Content(id);
}
複製代碼

FromForm特性沒有對簡單類型的參數進行限制,因此能夠直接獲取參數,當formData中有多個參數須要綁定時,能夠寫成以下格式:app

[HttpPost]
public ActionResult HandlePost([FromForm] int id, [FromForm] string name, ....) { // 只須要增長參數的個數就能夠
    return Content(id);
}
複製代碼
相關文章
相關標籤/搜索