【发布时间】:2018-07-10 03:58:58
【问题描述】:
我通过 C# 控制台应用程序将 IdentityServer4.Models.Client 类型的 httpPost 参数“client”发送到 C# web api,client 始终为 null。
如果我使用相同的代码发送不同的对象,则可以正常接收参数。这似乎是 Identity Server 4 特有的问题,我不知道发生了什么。
服务器代码:
[HttpPost]
public JsonResult Post(IdentityServer4.Models.Client client){
return Json(new { result = true });
}
客户端代码:
private static async Task Register(string clientName){
var controllerName = "BasicClient";
var basicClientApi = string.Format("http://localhost:5100/api/{0}", controllerName);
using (var httpClient = new HttpClient()){
var clientData = new IdentityServer4.Models.Client();
var client = new { client = clientData };
client.client.ClientName = clientName;
var json = JsonConvert.SerializeObject(client);
var content = new StringContent(json, Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.PostAsync(basicClientApi, content);
if (!response.IsSuccessStatusCode)
{
Console.WriteLine(response.StatusCode);
}
else
{
var rawResponse = await response.Content.ReadAsStringAsync();
JObject o = JObject.Parse(rawResponse);
Console.WriteLine(o.ToString());
}
}
}
编辑 应用 [FromBody] 并解包对象后,我仍然在接收 Web API 中为客户端获取 null。不过,有一件事引起了我对控制台应用程序调试屏幕的注意。请参见下图:
实际的客户端变量在控制台应用程序中为空,但 JsonConvert 能够将其序列化为某种东西。这是关于什么的?
【问题讨论】:
-
client = new { client = clientData };- 为什么要将模型包装在匿名对象中?您只需序列化您的Client对象,无需任何包装。 -
@FedericoDipuma 我完全错过了。包装将是一个问题。你应该把它作为答案。
标签: c# asp.net-core identityserver4 asp.net-core-webapi