【问题标题】:Get method not showing data in WebAPI获取方法未在 WebAPI 中显示数据
【发布时间】:2014-09-15 05:48:12
【问题描述】:

我正在学习 webapi。我正在运行我的 webapi 项目并点击 url localhost:54099/api/values

但是 Get 没有执行。我看不到数据。我在哪里做错了?当我点击 url 时,下面的弹出窗口显示,但我既不能保存也不能打开它。 当我在 Chrome 中点击相同的 url 时,我收到了错误

尝试创建“ValuesController”类型的控制器时出错。确保控制器有一个无参数的公共构造函数。

ValuesController 中的WebAPI 方法

  public IEnumerable<Book> Get()
            {
                var Books = iLibrary.GetBooks();
                return Books.ToList();
            }

WebApiConfig

 public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

【问题讨论】:

  • 这个问题发生在ie only..test it on chrome or other browser
  • 如果您想使用外部客户端应用程序来测试您的 API,您应该熟悉 Fiddler 之类的东西。还可以考虑编写单元和集成测试,这样您就可以断言您的期望,而不是使用外部应用手动确认它们。

标签: asp.net asp.net-mvc rest asp.net-web-api


【解决方案1】:

您的端点已正确执行并且似乎返回了数据。您看到的是 Internet Explorer 显示您返回的数据(我假设为 JSON 或 XML)的默认行为,即将其下载为文件。

为此使用 Chrome/Firefox。根据您是返回 JSON 还是 XML,您可能还希望使用在浏览器 s.t. 中格式化响应的插件。它更具可读性。比如

【讨论】:

    【解决方案2】:

    我找到了解决方案。我使用了错误的 dll 来解决依赖注入。我使用的是 Unity.MVC4,但由于它是一个 webapi 项目,我必须使用 Unity.WebAPI。

    【讨论】:

      猜你喜欢
      • 2017-07-26
      • 1970-01-01
      • 2022-11-23
      • 1970-01-01
      • 2020-04-03
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2023-03-16
      相关资源
      最近更新 更多