数据模型未显示在HttpResponseMessage中

时间:2017-07-20 22:11:31

标签: c# asp.net .net asp.net-core asp.net-core-webapi

我试图从.NET Core MVC应用程序进行简单的API调用:

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调用,所以我不确定它是怎么回事。

1 个答案:

答案 0 :(得分:3)

  

究竟是什么回复,为什么我的回复中的模型列表不是?

您正在服务器端混合使用Web API 2和Core。您看到的数据是序列化的HttpResponseMessage,它不再是框架的一部分,因此在从操作返回时它将其视为普通对象。

您需要使用.Net-Core的新语法

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

    [...] // populate resultObjects with data

    return Ok(resultObjects);
}