2017-07-20 35 views
2

我試圖讓從.NET核心MVC應用程序的簡單API調用:數據模型沒有出現在HttpResponseMessage

using (var client = new HttpClient()) 
{ 
    client.BaseAddress = new Uri("http://localhost:49897"); 

    var response = client.GetAsync("some-route").Result; 
    var dataString = response.Content.ReadAsStringAsync().Result; // Unexpected data here. See below. 

    [...] // deserialize dataString 
} 

client.GetAsync(route)成功擊中API操作方法,最終做到這一點:

public HttpResponseMessage Get([FromUri] BindingModel bindingModel) 
{ 
    List<SomeModel> resultObjects; 

    [...] // populate resultObjects with data 

    return Request.CreateResponse(HttpStatusCode.OK, resultObjects, new JsonMediaTypeFormatter()); 
} 

dataString最終等於這個:

"{\"version\":{\"major\":1,\"minor\":1,\"build\":-1,\"revision\":-1,\"majorRevision\":-1,\"minorRevision\":-1},\"content\":{\"objectType\":\"System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e\",\"formatter\":{\"indent\":false,\"serializerSettings\":{\"referenceLoopHandling\":0,\"missingMemberHandling\":0,\"objectCreationHandling\":0,\"nullValueHandling\":0,\"defaultValueHandling\":0,\"converters\":[],\"preserveReferencesHandling\":0,\"typeNameHandling\":0,\"metadataPropertyHandling\":0,\"typeNameAssemblyFormat\":0,\"typeNameAssemblyFormatHandling\":0,\"constructorHandling\":0,\"contractResolver\":null,\"equalityComparer\":null,\"referenceResolver\":null,\"referenceResolverProvider\":null,\"traceWriter\":null,\"binder\":null,\"serializationBinder\":null,\"error\":null,\"context\":{},\"dateFormatString\":\"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK\",\"maxDepth\":null,\"formatting\":0,\"dateFormatHandling\":0,\"dateTimeZoneHandling\":3,\"dateParseHandling\":1,\"floatFormatHandling\":0,\"floatParseHandling\":0,\"stringEscapeHandling\":0,\"culture\":{}}}}}" 

或者在JSON格式:

{ 
    version: { 
     major: 1, 
     minor: 1, 
     [...] 
    }, 
    content: { 
     objectType: "System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e" 
     formatter: { 
      indent: false, 
      serializerSettings: { 
       [...] 
      } 
     } 
    } 
} 

我的型號列表不存在一樣。

究竟是什麼被返回,爲什麼不是我的迴應模型列表?我已經看過幾個在線資源,而且我似乎正在以與他們展示的方式相同的方式進行操作。這是一個很棒的麪包和API調用,所以我不確定發生了什麼。

+0

你混合的Web API 2和核心。 – Nkosi

回答

3

究竟是什麼被返回,爲什麼不是我的響應模型列表?

您在服務器端混合使用Web API 2和Core。您看到的數據是序列化的HttpResponseMessage,它不再是框架的一部分,因此它在從操作返回時將其視爲正常對象。

您需要使用新的語法.Net的核心

public IActionResult Get([FromUri] BindingModel bindingModel) { 
    List<SomeModel> resultObjects; 

    [...] // populate resultObjects with data 

    return Ok(resultObjects); 
}