C# - 如何向多个 [FromForm] 发送信息?

C# - How to send information to multiple [FromForm]?

我有这样一个端点:

[HttpPost("DoWork")]
public async Task<ActionResult> DoWork([FromForm] string name, [FromForm] string uri) {
    ...
}

从另一端如何打包和发送该数据,它看起来像这样吗?

public void MyMethod(string name, string uri) {
    Dictionary<string, string> packet = new Dictionary<string, string>();
    packet.Add("name", name);
    packet.Add("uri", uri);

    var stringContent = new StringContent(JsonConvert.SerializeObject(packet), UTF8Encoding.UTF8, "application/json");
}

最好创建视图模型

public class ViewModel
{
public string Name {get; set;}
public string Uri {get; set;}
}

和行动

[HttpPost("DoWork")]
public async Task<ActionResult> DoWork([FromBody] ViewModel viewModel)
{
    ...
}

恕我直言,您创建内容的方式不需要 [FromForm],请尝试使用 [FromBody]

我通过使用 RestRequest 并在发送请求之前添加每个参数来完成它:

RestClient rC = new RestClient(apiUrl);
RestRequest rr = new RestRequest(Method.POST);
rr.AddParameter("name", name);
rr.AddParameter("uri", uri);
RestResponse response = (RestResponse)await rC.ExecutePostAsync(rr);