.net - 如何从 .NET Core MVC 调用具有多个参数的 API
问题描述
我正在尝试编写将调用现有 API 并检索一些数据的 .NET Core MVC 项目。对于只需要一个参数的 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。
解决方案
如果要添加多个参数作为查询字符串,可以这样做:
string newUrl=url+"?sessionId="+sessionId+"&&code="+"codedata";
var request = new HttpRequestMessage(HttpMethod.Post, newUrl);
推荐阅读
- c# - 如何在 C# 中获取引用的 dll 的完整路径
- kubernetes - Kubernetes 中的 Prometheus HA (AKS)
- windows - Azure Pipelines:如何使任务依赖于先前的任务?
- entity-framework - .NetCore 3.1 中的 EntityFramework 和多个 DBContext
- python - 如何修复错误“'django-admin'不被识别为内部或外部命令”?
- matplotlib - CartoPy GeoAxes 之间的 PyPlot ConnectionPatch
- python - 使用 s3a 协议从本地 PySpark 上的 S3 读取镶木地板文件时出现异常
- java - 指定 @Morph 参数时无法运行 ByteBuddy 拦截器
- python - 设置运行函数 Python 的时间限制
- websocket - 如何通过 @MessageMapping 使用指定的用户 url 将消息传递给控制器?