Web API不会返回对象

时间:2014-10-17 02:45:57

标签: c# asp.net-web-api

我有一个非常简单的Web API应用程序。一切似乎都在使用基本类型。你不会找到任何花哨的身份验证或任何东西,但我可以在IIS Express上运行:

  • http:// localhost:25095 / Workbench / GetObject,或者:
  • http:// localhost:25095 / Workbench / GetNumber

当我启动此Web应用程序时,我可以将浏览器指向GetNumber并在窗口中查看15。但是,当我指向GetObject时,我看到WebAPI.DemoApp.SampleObject。这不一定会打扰我,除非我为什么感到困惑。

我有代码(显示进一步向下),据称强制Web API返回JSON。因此,无论是GetNumber还是GetObject,我都希望返回类似(Pseudocode)的内容:

  • {15}
  • {名称:JoeBob}

无论哪种方式,我的控制台应用程序的ReadAsStringAsync都会产生相同的结果,而ReadAsAsync会产生错误:

  • 没有MediaTypeFormatter可用于从媒体类型为“text / html”的内容中读取“SampleObject”类型的对象

我的控制台应用非常简单:

static void Main(string[] args)
{

    using (var client = new HttpClient())
    {

        client.BaseAddress = new Uri("http://localhost:25095/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        //HttpResponseMessage response = client.GetAsync("Workbench/GetObject").Result;
        HttpResponseMessage response = client.GetAsync("Workbench/GetNumber").Result;

        //SampleObject getObject = response.Content.ReadAsAsync<SampleObject>().Result;
        var getNumber = response.Content.ReadAsStringAsync().Result;
        Console.WriteLine(getNumber);

        Console.Read();

    }
}

我想提一下,这个项目是作为生成的ASP.Net Web API项目(没有Azure)开始的。一切都从那里开始走下坡路。我认为我强迫Web API只返回JSON,但这一切都没有像我期望的那样工作。

字面上所有代码都在Global.asax.cs文件中,我在下面复制/粘贴:

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Mvc;

namespace WebAPI.DemoApp
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            System.Web.Routing.RouteTable.Routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}",
                defaults: new { controller = "Workbench", action = "GetObject", id = UrlParameter.Optional }
            );

            var jsonFormatter = new JsonMediaTypeFormatter();
            GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
        }
    }

    public class JsonContentNegotiator : IContentNegotiator
    {
        private readonly JsonMediaTypeFormatter _jsonFormatter;

        public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
        {
            _jsonFormatter = formatter;
        }

        public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
        {
            var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
            return result;
        }
    }

    public class WorkbenchController : Controller
    {
        public SampleObject GetObject()
        {
            return (new SampleObject() { Name = "JoeBob" });
        }
        public int GetNumber()
        {
            return 15;
        }
    }
}

Web.config同样简单:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings></appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5"/>
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.0.0" newVersion="5.2.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

除了精简版参考文献(我删除了所有OWIN参考文献)之外,项目中没有任何其他内容。

我的目标只是将我的对象转到我的控制台应用程序。

PS:SampleObject存在于两个项目之间共享的单独DLL中。

    [DataContract]
    public class SampleObject
    {
        [DataMember]
        public string Name { get; set; }
    }

1 个答案:

答案 0 :(得分:1)

原来,要返回对象,您需要继承ApiController,而不是Controller。这也意味着我的App_Start必须:

GlobalConfiguration.Configure(WebApiConfig.Register);

执行您在默认Web API App中看到的配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}