【问题标题】:showing json from Web API controller on Razor view在 Razor 视图上显示来自 Web API 控制器的 json
【发布时间】:2014-06-05 08:39:48
【问题描述】:

我正在开发一个 asp.net MVC 5 应用程序。我创建了一个返回药物列表的 Web API 2 控制器。现在我想显示它们以供查看。我创建了另一个名为 homecontroller 和索引操作方法的控制器(因为我认为 api 控制器不能有操作方法)。我创建了索引视图。在这种观点中,我想展示药物清单。我点击了这个链接http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

我正在尝试这段代码:

var uri = '/api/Medicines';

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(uri)
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

但在浏览器控制台中得到 404。

这是 Web APi 控制器方法:

public class MedicinesController : ApiController
{
    public IEnumerable<Medicine> GetMedicines()
    {
        Random rnd = new Random();
        return medicines.OrderBy(x => rnd.Next()).ToList();
    }
}

路线配置为:

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

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

请建议如何解决此问题。我需要 json 格式的药品清单。

谢谢

【问题讨论】:

  • 你能显示你的路线配置吗?
  • 请检查更新的问题
  • 您在 Medicines 控制器中还有其他名称以“Get”开头的操作吗?
  • 检查我的答案的更新。

标签: c# asp.net asp.net-mvc json razor


【解决方案1】:

如果路由配置类似于

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

但如果你有这样的(教程中有两个版本)

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

您还必须在 uri '/api/Medicines/Medicines' 中指定操作名称。

更新

我使用 WebApi 创建了新的 MVC 5 项目,并且一切正常,没有任何问题和黑客攻击。您不能尝试与您的解决方案进行比较 - test repo on github

【讨论】:

    【解决方案2】:

    如果您有标准路线配置并且不使用任何区域等,您的 uri 应该是

    var uri = '/Medicines/GetMedicines'
    

    正如 Joanvo 所说,您可能需要 allowGet 设置作为回报。像这样:

    return Json(medicines.OrderBy(x => rnd.Next()), JsonRequestBehavior.AllowGet);
    

    【讨论】:

    • 请记住,我在 home/index 视图中使用此 url,而我的 api 控制器是医学控制器
    • 在您的路线配置中,您没有提及任何有关操作的内容。并且默认没有任何动作。你能把它改成类似“url:”{controller}/{action}/{id}“,默认值:new {controller =“Home”,action =“Index”,id = UrlParameter.Optional},”?再试一次?
    • @Antonio97 WebApi != Asp.NET MVC。您建议更改 MVC 路由,但 DotnetSparrow 在 WebApi 路由方面存在问题。
    猜你喜欢
    • 2012-07-19
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    相关资源
    最近更新 更多