You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebApi POST方法接收string参数始终为null问题求助

Fixing Null json Parameter in Your Web API POST Method

Hey there! I’ve run into this exact issue before, so let’s break down why your json parameter is coming through as null and how to fix it.

The Root Cause

When you use [FromBody] string json in your Web API method, ASP.NET expects the request body to be a raw JSON string (not a JSON object). Right now, you’re sending a full JSON object:

{ "ListSessionId": [ "180416073256DGQR10", "180416091511DGQR10" ] }

Web API can’t automatically map this object to a string type, so it sets the parameter to null by default.

This is the cleanest, most maintainable approach. Create a model class that matches your JSON structure:

public class SessionRequest
{
    public List<string> ListSessionId { get; set; }
}

Then update your API method to accept this model instead of a string:

[HttpPost]
public HttpResponseMessage GetOrderDataBySessionId([FromBody] SessionRequest request)
{
    // Now you can access request.ListSessionId directly
    // No manual JSON parsing required!
}

When you send your original JSON body, Web API will automatically bind it to the SessionRequest object, and your parameter will no longer be null.

Solution 2: Send a Raw JSON String (If You Must Keep the String Parameter)

If you absolutely need to retain the string json parameter, you need to wrap your JSON object in quotes to make it a valid JSON string. Your request body should look like this:

"{ \"ListSessionId\": [ \"180416073256DGQR10\", \"180416091511DGQR10\" ] }"

Or in code (using Newtonsoft.Json for serialization):

var payload = new { ListSessionId = new List<string> { "180416073256DGQR10", "180416091511DGQR10" } };
var jsonString = JsonConvert.SerializeObject(payload);
// Send jsonString as the request body with Content-Type: application/json

Note: This approach is less ideal because you’ll have to manually parse the string later, and you lose all the benefits of strong typing (like automatic validation and intellisense).

Quick Sanity Check

Double-check that your RestClient is setting the Content-Type header correctly to application/json—it’s easy to miss this, and it can cause binding issues even if everything else is set up right!

内容的提问来源于stack exchange,提问作者Huma Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:13:25