PostAsJsonAsync 后 WebApi 方法中的对象为 null

Jon*_*Jon 2 c# asp.net-mvc http-post asp.net-web-api asp.net-web-api2

我正在向 WebApi 方法发布一个对象。我是PostAsJsonAsync用来做这个的。

public async Task<HttpResponseMessage> PostAsync(string token, ServiceCall call)
{
    var client = new HttpClient();
    client.SetBearerToken(token);

    var response = await client.PostAsJsonAsync(Uri + "id/nestedcall", call);

    return response;
}
Run Code Online (Sandbox Code Playgroud)

call当我发布它时,我传递的对象不为空。

[HttpPost]
[Route("id/nestedcall")]
public async Task<IHttpActionResult> NestedCall([FromBody]ServiceCall call)
{
    // call is null here
}
Run Code Online (Sandbox Code Playgroud)

但是,它在我的 API 方法中为 null。我似乎无法弄清楚为什么我遵循的所有示例都使用这种格式。

为什么调用对象没有被 web api 拾取?

编辑

这里是ServiceCall对象。它位于一个单独的类库中,并且 Web 应用程序和 API 中都包含一个引用。

public class ServiceCall
{
    public ServiceCall(Service service, string grantType)
    {
        ClientId = service.Id;
        ClientSecret = service.Secret;
        Uri = service.Uri;
        Scope = service.Scope;
        GrantType = grantType;
    }

    public ServiceCall(string clientid, string clientsecret, string uri, string scope, string grantType)
    {
        ClientId = clientid;
        ClientSecret = clientsecret;
        Uri = uri;
        Scope = scope;
        GrantType = grantType;
    }

    public string ClientId { get; set; }
    public string ClientSecret { get; set; }
    public string Uri { get; set; }
    public string Scope { get; set; }
    public string GrantType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

我看到后的WebAPI方法对象空PostAsJsonAsync由于系列化。更好地使用PostAsync如下:

        var obj = new MyClass()
        {
            MyProperty = 11
        };

        using (var client = new HttpClient())
        {
            string inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj); 
            HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8, "application/json");
            HttpResponseMessage response1 = client.PostAsync("http://localhost:60909/api/home/Test", inputContent).Result;
            if (response1.IsSuccessStatusCode)
            {

            }
        }
Run Code Online (Sandbox Code Playgroud)