简体   繁体   English

在ASP.NET Core 2.x中,IdentityServer4.Models.Client作为httppost参数始终为null

[英]IdentityServer4.Models.Client as httppost parameter always null in aspnet core 2.x

I am sending an httpPost parameter "client" of type IdentityServer4.Models.Client via a C# console application to a C# web api and client is always null . 我通过C#控制台应用程序向C#Web api发送类型为IdentityServer4.Models.Client的httpPost参数“ client”。client 始终为null

If I send a different object using the same code, the parameter is received just fine. 如果我使用相同的代码发送另一个对象,则可以很好地接收参数。 This seems to be a problem specific to Identity Server 4 and I don't know what's going on. 这似乎是Identity Server 4特有的问题,我不知道发生了什么。

Server code: 服务器代码:

[HttpPost]        
public JsonResult Post(IdentityServer4.Models.Client client){   

    return Json(new { result = true });
}

Client code: 客户代码:

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());
            }
        }
    }

EDIT After applying [FromBody] and unwrapping the object, I am still getting null for client in the receiving Web API. 编辑应用[FromBody]并解开对象后,接收Web API的客户端仍然为null。 One thing caught my eye on the console application debug screen though.. see the image below: 有一件事让我注意到了控制台应用程序调试屏幕..参见下图:

在此处输入图片说明

The actual client variable is null in the console application, yet JsonConvert was able to serialize it into something. 在控制台应用程序中,实际的客户端变量为null,但是JsonConvert能够将其序列化为某种东西。 What's that about? 那是什么意思

You are wrapping your model inside an anonymous object, which will turn its JSON representation into something which has nothing in common with your original Client class. 您将模型包装在一个匿名对象中,这会将其JSON表示形式转换为与原始Client类没有任何共同之处。

This: 这个:

var clientData = new IdentityServer4.Models.Client();
var client = new { client = clientData };
client.client.ClientName = clientName;

var json = JsonConvert.SerializeObject(client);

Will result in a JSON similar to the following: 将产生类似于以下内容的JSON:

{
    "client": { 
        "clientName": "foo",
        "anotherProperty": "bar",
        // other properties omitted for brevity
    }
}

But what you really want is just the Client object: 但是,您真正想要的只是Client对象:

{ 
    "clientName": "foo",
    "anotherProperty": "bar",
    // other properties omitted for brevity
}

Do not wrap your clientData , just serialize it directly to follow the model inside your MVC Action Method: 不要包装您的clientData ,只需直接对其进行序列化以遵循MVC Action Method中的模型:

var clientData = new IdentityServer4.Models.Client();
clientData.ClientName = clientName;

var json = JsonConvert.SerializeObject(clientData);

For everything to be working, you have to tell the model binder explicitly where to expect the data. 为了使所有工作正常进行,您必须明确告诉模型绑定器数据在哪里。

Use [FromBody] attribute on the model. 在模型上使用[FromBody]属性。

[FromBody] : Use the configured formatters to bind data from the request body. [FromBody] :使用配置的格式化程序来绑定来自请求正文的数据。 The formatter is selected based on content type of the request. 根据请求的内容类型选择格式化程序。

[HttpPost]        
public IActionResult Post([FromBody]IdentityServer4.Models.Client client) {

    return Json(new { result = true });
}

Reference Model Binding in ASP.NET Core ASP.NET Core中的参考模型绑定

You're not going to believe this, but ultimately the reason why IdentityServer.Models.Client was null in the Web Api post parameter was because the class is decorated with [DebuggerDisplay("{ClientId}")] and I did not provide a ClientId in my test application, so it was always showing up as null when in fact it actually WAS THERE THE WHOLE TIME. 您不会相信这一点,但最终导致在Web Api post参数中IdentityServer.Models.Client为null的原因是因为该类用[DebuggerDisplay(“ {ClientId}”)]装饰,而我没有提供我的测试应用程序中的ClientId,因此实际上实际上是整时间出现时,它始终显示为null。 I am glad this issue is behind me, but I am very angry about this "feature". 我很高兴这个问题在我身后,但是我对这个“功能”感到非常生气。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM