我正在调用 http://localhost/AppTools.WebAPI/api/BulletinBoard/GetMessagesForApp/AppName
,但它返回 404 错误。我认为这与路由有关,但我不确定。
这是我的 BulletinBoard Controller 中的 Web API 方法:
[HttpGet]
public HttpResponseMessage GetMessagesForApp(string id)
{
// get current, valid messages
var messages = (from i in db.BulletinBoards
where i.AppId == id &&
DateTime.Today >= i.DisplayFrom &&
DateTime.Today <= i.DisplayTo &&
i.IsActive == true
select new
{
Message = i.Message,
IntervalId = i.IntervalId,
Interval = i.Interval.IntervalDescription,
Timeout = i.Timout,
})
.ToList();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, messages);
return response;
}
这是我的 RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
标准的 Get()
和 Get(int id)
工作正常,我没有更改方法名称或签名。 Get()
返回完整的记录列表,Get(int id)
返回特定记录。我希望 GetMessagesByApp(string id)
返回特定于某个 AppName 的记录列表。你能告诉我为什么这不起作用吗?
最佳答案
Here's my RouteConfig.cs:
RouteConfig.cs
文件用于定义 ASP.NET MVC Controller 的路由。这些与您的 Web API Controller 使用的路由完全无关。它们在 WebApiConfig.cs
文件中定义。
因此请确保您已在正确的位置声明了您的路线:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiWithActionName",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
请注意,我在默认路由之前添加了一个自定义路由,这将允许您实现所需的 url 模式。
然后您可以执行以下 Controller 操作,该操作将正常工作:
// GET /api/controllername
// GET /api/controllername/get
[HttpGet]
public HttpResponseMessage Get()
{
...
}
// GET /api/controllername/get/123
[HttpGet]
public HttpResponseMessage Get(int id)
{
...
}
// GET /api/controllername/GetMessagesForApp/abc
[HttpGet]
public HttpResponseMessage GetMessagesForApp(string id)
{
...
}
关于c# - 尝试在我的 WebAPI 上调用特定的 GET 方法,但未找到 HTTP 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20861706/