简体   繁体   中英

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 .

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.

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. 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. 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.

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:

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

But what you really want is just the Client object:

{ 
    "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:

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] : Use the configured formatters to bind data from the request body. 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

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. I am glad this issue is behind me, but I am very angry about this "feature".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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