【发布时间】:2021-09-05 05:06:49
【问题描述】:
我正在尝试编写 .NET Core MVC 项目,该项目将调用现有 API 并检索一些数据。对于只需要一个参数的 API 后调用,我编写了以下代码:
public async Task<GenericResultType<string>> CallValidate(string url, string sessionId)
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
if (!string.IsNullOrEmpty(sessionId))
request.Content = new StringContent(sessionId, Encoding.UTF8, "application/json");
else
throw new BaseException<PublicWebExceptions>(PublicWebExceptions.SessionIdNullOrEmpty);
var client = _clientFactory.CreateClient();
HttpResponseMessage response = await client.SendAsync(request);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = JsonConvert.DeserializeObject<GenericResultType<string>>(await response.Content.ReadAsStringAsync());
if (result != default)
{
return result;
}
}
throw new BaseException<PublicWebExceptions>(PublicWebExceptions.InvalidCall);
}
我的问题是,这是一种有效的方法吗?如何调用具有多个字符串参数的 post 方法,例如,如果我有字符串 sessionId 和字符串代码,我如何将它们都传递给 API。
【问题讨论】:
-
API 期望如何传递参数?在 JSON 正文中还是在查询字符串中?你是如何尝试传递多个参数的?这种方法有效吗?
-
API 期望参数为查询字符串
-
既然您使用的是 Core MVC,为什么不使用模型来保存这两个值,并在您的视图上创建一个表单呢?有很多方法。进行 AJAX 调用是另一回事。
标签: .net asp.net-mvc api asp.net-core .net-core