c# - 数据模型未显示在 HttpResponseMessage 中

标签 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 调用,所以我不确定发生了什么。

最佳答案

What exactly is being returned, and why isn't my list of models in the response?

返回的是 HttpResponseMessage 的 JSON 序列化版本,因为虽然 Web API 2 专门处理这种类型,但 ASP.NET Core Web API 不会

准确地说,ASP.NET Core web API supports returning the following types :

  • IActionResult
  • ActionResult<T>
  • <任何其他类型>

前两个被特殊对待,但第三个导致该类型被 JSON 序列化并返回,正如您所见。

相比之下,Web API 2 supports the following special return types :

  • void
  • HttpResponseMessage
  • IHttpActionResult
  • <任何其他类型>

正确的解决方案是更新您的代码以使用自定义 IActionResult实现而不是返回原始 HttpResponseMessage秒。 You may find this guide aids you in doing so - 特别是 Microsoft.AspNetCore.Mvc.WebApiCompatShim NuGet 包有一个 ResponseMessageResult class允许您从这个转换您的 Web API Controller 方法:

public HttpResponseMessage Foo(Bar quux)
{
    return new BazHttpResponseMessage();
}

为此:

public IActionResult Foo(Bar quux)
{
    return new ResponseMessageResult(new BazHttpResponseMessage());
}

这应该允许您当前的代码按原样工作。

关于c# - 数据模型未显示在 HttpResponseMessage 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45226019/

相关文章:

c# - EntityFramework 和带有对象数组的自定义类(一对多)

c# - 将 Microsoft Word 智能引号转换为直引号

c# - 如何在 C# 中制作全局键盘钩子(Hook)

c# - 免费安装程序是否可以轻松地将应用程序安装为 Windows 服务?

.net - 添加对面向 .NET 标准 2.0 的类库的引用到面向 .NET 标准 4.5 的 Xamarin PCL

.net - 如何以编程方式清除 MSMQ 系统队列日志?

c# - 使用 Ninject 查找实现通用接口(interface)的类

c# - Linq 查询以选择最高记录

c# - 如何将位图另存为图标?

c# - 多列索引搜索 Microsoft.Isam.Esent