首页 > 解决方案 > 如何从 .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。

标签: .netasp.net-mvcapiasp.net-core.net-core

解决方案


如果要添加多个参数作为查询字符串,可以这样做:

string newUrl=url+"?sessionId="+sessionId+"&&code="+"codedata";
var request = new HttpRequestMessage(HttpMethod.Post, newUrl);

推荐阅读