我正在尝试将API控制器添加到MVC5应用程序中。但是我收到错误" RouteData必须包含一个名为' action'使用非空字符串值。"当我导航到路线时:http://localhost/DataAPI/Community/Get/
应用程序似乎并不想识别API控制器 - 如果我将操作添加到路由默认值,我会收到404错误。当我用标准控制器替换它(并将默认操作添加到路由数据)时,我可以获取数据。我错过了什么吗?
控制器位于Controllers / DataAPI子目录中:
using System.Web.Http;
using System.Net.Http;
namespace ERP.Controllers.DataAPI
{
public class CommunityController : ApiController
{
PCSEntities db = new PCSEntities();
public IEnumerable<Community> Get(Guid ApiKey)
{
return db.Communities.AsNoTracking().Take(10);
}
}
}
这是我的路线配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
#region DataAPI
var ns = new[] { "ERP.Controllers.DataAPI" };
routes.MapRoute(
name: "DataAPI",
url: "DataAPI/{controller}/{ApiKey}/{id}",
defaults: new { ApiKey = Guid.Empty, id = UrlParameter.Optional },
namespaces: ns
);
#endregion
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
答案 0 :(得分:0)
尝试在RouteConfig中替换您的路线,如下所示:
routes.MapHttpRoute(
name: "DataAPI",
routeTemplate: "DataAPI/{controller}/{ApiKey}/{id}",
defaults: new { ApiKey = Guid.Empty, id = UrlParameter.Optional }
);
此外,使用Web API时,不应显式调用Get
方法。
因此,在您的情况下,您可以将GUID作为参数传递,如下所示: http://localhost/DataAPI/Community/6c4058a6-7edb-46c0-9d81-1c508c729f5b
答案 1 :(得分:0)
查看以下教程
using System.Web.Http;
using System.Net.Http;
namespace ERP.Controllers.DataAPI
{
public class CommunityController : ApiController
{
PCSEntities db = new PCSEntities();
public IEnumerable<Community> GetCommunities(Guid ApiKey)
{
return db.Communities.AsNoTracking().Take(10);
}
}
}
您正在显示MVC的路由配置而不是Web Api
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
#region DataAPI
var ns = new[] { "ERP.Controllers.DataAPI" };
config.Routes.MapHttpRoute(
name: "DataAPI",
routeTemplate: "DataAPI/Community/{ApiKey}",
defaults: new {controller= "Commmunity", action = "GetCommunities", ApiKey = Guid.Empty},
namespaces: ns
);
#endregion
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}