Http PostAsJsonAsync获取空参数(DTO)

时间:2019-09-23 10:56:47

标签: c# post client-server httpclient dto

我正在尝试将DTO类对象传递给服务器,但是该对象被发送为空

DTO:

public class FileSettings
{
    public int SetID { get; set; }
    public int RunID { get; set; }
    public int FileID { get; set; }
}

客户:

string URL = "http://localhost:9000";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);

FileSettings data = new FileSettings();
data.SetID = setID;
data.RunID = runID;
data.FileID = fileID;

HttpContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.PostAsJsonAsync("/api/output/ApplyFileRule", content);

服务器:

public void ApplyFileRule([FromBody] FileSettings data)
{
    var runID = data.RunID;
    ...
}

1 个答案:

答案 0 :(得分:1)

更改这些:

FileSettings data = new FileSettings();
FileSettings.SetID = setID;
FileSettings.RunID = runID;
FileSettings.FileID = fileID;

HttpContent content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json");

对此:

FileSettings data = new FileSettings();
data.SetID = setID;
data.RunID = runID;
data.FileID = fileID;

HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");