2016-06-14 37 views
0

我正在向WebApi方法发布对象。我使用PostAsJsonAsync来做到这一点。PostAsJsonAsync后的WebApi方法中的对象null

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

对象call说我路过不为空,当我将它张贴。

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

但是它在我的API方法中为空。我似乎无法解决为什么我所遵循的所有例子都使用这种格式。

为什么调用对象不能被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; } 
} 
+0

您能否粘贴异常消息。然而,看起来你的模型绑定不起作用 – Arsene

+0

也在调试模式下运行它,并进入代码,你会发现更多关于你正在发送的数据 – Arsene

+0

他没有得到一个异常消息,只是接收null,发生在我身上几次,它可能有不同的原因。既然你说方法的相同签名在其他情况下有效,我会问你是否发送和接收完全相同的sams类型,或者只是具有相同名称的类,但是在不同的命名空间中。如果第二个变体,请检查您是否将TypeNameHandling设置为auto或全部,我想在Global配置中,如果我还记得的话。 – meJustAndrew

回答

0

使用前缀Stackify我能诊断该串行器被抛出异常:

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 

然而,非常有益,而不是告诉我,控制器发生异常简单地给了我一个空目的。

正如例外情况所暗示的,解决方案是添加一个默认构造函数(或者至少有一个serialiser可以理解)。

public ServiceCall() 
{ 

} 
0

看起来像JSON序列化可能会失败。顺便说一句,删除[FromBody]并尝试没有它像下面。 PostAsJsonAsync方法将ServiceCall对象序列化为JSON,然后在POST请求中发送JSON负载。

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

我已经试过了,没有'[FromBody]',因为它是我最初无法使用时添加的。但是,我看到很多例子都使用它。 – Jon