【问题标题】:Send JSON to GET method in C#在 C# 中将 JSON 发送到 GET 方法
【发布时间】:2020-03-10 05:57:39
【问题描述】:

我有一个带有如下控制器的 Web 服务:

    [HttpGet]
    [Customizing.RequestSizeLimit(1048576)] // 1 MB
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status422UnprocessableEntity)]
    public async Task<IActionResult> ValidateTicketAsync([FromBody]KerberosTicketDto ticket)
    {//code in here//}

Swagger 声明 Web 服务接受:

{
"ticket": "string"
}

从客户端,我得到一个 Kerberos 票并将其转换为字符串:

KerberosSecurityTokenProvider tokenProvider = new KerberosSecurityTokenProvider(ServiceServer, TokenImpersonationLevel.Identification);
KerberosRequestorSecurityToken token = tokenProvider.GetToken(TimeSpan.FromMinutes(1)) as KerberosRequestorSecurityToken;
...
tokenString = Convert.ToBase64String(token.GetRequest());

然后尝试将数据发送到网络服务器,并返回响应代码(即希望为 200):

WebClient webClient = new WebClient();
webClient.QueryString.Add("ticket", tokenString);
//webClient.QueryString.Add("spn", ServiceServer);
string result = webClient.DownloadString(urlTest);

然后调试窗口向我发送这个:

[10:40:21 DBG] Attempting to bind parameter 'ticket' of type 'Kerberos.TicketValidator.WebApi.Model.KerberosTicketDto' using the name 'ticket' in request data ...
[10:40:21 DBG] Rejected input formatter 'Microsoft.AspNetCore.Mvc.Formatters.JsonPatchInputFormatter' for content type 'null'.
[10:40:21 DBG] Rejected input formatter 'Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter' for content type 'null'

Web 服务获取的参数似乎不是它预期的类型。

谁能帮我把它转换成正确的类型?或者如何首先将其作为正确的类型发送?

谢谢!

【问题讨论】:

  • FromBodyHttpGet ... 迷人
  • 我没有编写api,我正在测试它。
  • swagger 显示了一些 json ...尝试像在 HTTP 请求的 body 中那样大摇大摆地发送 json ...只有一个问题 HTTP GET 不打算有 body
  • 直截了当:public async Task&lt;IActionResult&gt; ValidateTicketAsync([FromBody]KerberosTicketDto ticket) 不在你的控制之下,你只应该测试它。对吗?
  • 如果你得到任何东西,应该是POST 请求FromBody

标签: c# web-services asp.net-core http-headers webclient


【解决方案1】:

我认为您需要将票作为具有名为ticket 的属性的对象发送,而不是作为字符串发送。

HttpClient 可能类似于以下内容。

var tokenJson = jsonSerializer.Serialise(new {token = tokenString });
using(var client = new HttpClient())
{
  var req = new HttpRequestMessage
  {
      Method = HttpMethod.Get,
      RequestUri = new Uri("some url"),
      Content = new StringContent(tokenJson, Encoding.UTF8, ContentType.Json),
  };

   var res = await client.SendAsync(req).ConfigureAwait(false);
   res.EnsureSuccessStatusCode();

   var res = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}

【讨论】:

  • 谢谢,我试试看。
猜你喜欢
  • 2015-11-11
  • 1970-01-01
  • 2021-08-17
  • 2021-12-16
  • 2010-12-04
  • 2013-07-10
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
相关资源
最近更新 更多