【发布时间】:2017-08-17 13:52:00
【问题描述】:
作为 MVC web api 中的菜鸟,我可能缺少一些非常明显的东西..
但是,在我的ProjectController 中,我有以下带有属性的方法(我知道这种方法应该是 POST,但只是容易测试......):
[Route("api/projects/archive/{id:int}")]
[HttpGet]
public void Archive(int id)
{
_projectService.Archive(id);
}
但是,当我打开我的网址时,例如:
http://localhost:49923/api/projects/archive/1
页面只是重定向到当前的 URL,并且没有调用归档方法。我在方法上也有一个断点来验证它没有被命中。
我最好的猜测是我还必须更新我的默认 web api 路由配置,但我只是假设路由属性就足够了吗?
这是我的 web api 路由配置:
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});
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new MediaTypeHeaderValue("text/html"));
}
我在这里做错了什么? :-)
编辑:
说明 1 - 我的 ProjectController:
public class ProjectsController : ApiController
{
private ProjectService _projectService;
public ProjectsController()
{
_projectService = new ProjectService();
}
[Route("api/projects/archive/{id:int}")]
[HttpGet]
public void Archive(int id)
{
_projectService.Archive(id);
}
}
澄清 2 - 重定向:
假设我站在首页 (/) 上。然后我转到 URL“http://localhost:49923/api/projects/archive/1”,它只会重新加载页面并将我的背部留在主页。
【问题讨论】:
-
澄清
The page simply redirects to the current URL, and the archive method is not called.不清楚。同时显示控制器。
标签: c# asp.net-mvc asp.net-web-api2 asp.net-web-api-routing