Mark Ku's Blog
首頁 關於我
Http post request FromBody string always binding null in dotnet
NETCORE
Http post request FromBody string always binding null in dotnet
Mark Ku
Mark Ku
November 05, 2022
1 min

Problem

[HttpPost]
public string Book([FromBody] string test) // binding string always is null 
{
return test;
}

Root cause

When having [FromBody]attribute, the string sent should not be a raw string, but rather a JSON string as it includes the wrapping quotes:

'test string' or "test string"

So you can use JSON.stringify()

JSON.Stringify('test string') // will be => "test string"

But cannot do JSON.Stringify twice

let x= JSON.stringify(JSON.stringify('test string')) // will be => '"\\"test string\\""'

Avoid execute twice

export const isJsonString = (str: string) => {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }
  return true;
};

Tags

Mark Ku

Mark Ku

Software Developer

9年以上豐富網站開發經驗,開發過各種網站,電子商務、平台網站、直播系統、POS系統、SEO 優化、金流串接、AI 串接,Infra 出身,帶過幾次團隊,也加入過大團隊一起開發。

Expertise

前端(React)
後端(C#)
網路管理
DevOps
溝通
領導

Social Media

facebook github website

Related Posts

淺談使用 Dotnet 開源 Yarp Revert Proxy 實現滾動式佈署 ( Rolling-update ) - Part's 1 設計思路
淺談使用 Dotnet 開源 Yarp Revert Proxy 實現滾動式佈署 ( Rolling-update ) - Part's 1 設計思路
July 02, 2022
1 min

Quick Links

關於我

Social Media