Object null in WebApi method after PostAsJsonAsync

寵の児 提交于 2020-12-14 06:54:45

问题


I am posting an object to a WebApi method. I'm using PostAsJsonAsync to do this.

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

The object call that I'm passing is not null when I post it.

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

However it is null in my API method. I can't seem to work out why as all of the examples I've followed use this format.

Why isn't the call object being picked up by the web api?

Edit

Here is the ServiceCall object. It is in a separate class library and a reference is included in both the web application and the 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; }
}

回答1:


I have seen Object null in WebApi method after PostAsJsonAsync due to serialization. Better to use PostAsync like below :

        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)
            {

            }
        }



回答2:


Using Prefix Stackify I was able to diagnose that the serialiser was throwing an exception:

Newtonsoft.Json.JsonSerializationException: Unable to find a constructor to use for type Core.Models.ServiceCall. A class should either have a default constructor, one constructor with arguments or a constructor marked with the JsonConstructor attribute. Path 'ClientId', line 1, position 12.
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewObject
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal
  at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize

However, very helpfully, rather than tell me that an exception occurred the controller simply gave me a null object.

As hinted by the exception the solution is to add a default constructor (or at least one the serialiser can understand).

public ServiceCall()
{

}



回答3:


looks like the JSON serialization may be failing. BTW, remove that [FromBody] and try without it like below. PostAsJsonAsync method serializes the ServiceCall object to JSON and then sends the JSON payload in a POST request.

public async Task<IHttpActionResult> NestedCall(ServiceCall call)
{
    // your code
}



回答4:


I run into exactly the same problem and had to do this to solve it:

using (var client = new HttpClient())
{
    client.SetBearerToken(token);
    var content = new StringContent(JsonConvert.SerializeObject(call), Encoding.UTF8, "application/json");

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


来源:https://stackoverflow.com/questions/37818405/object-null-in-webapi-method-after-postasjsonasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!