我正在调用网址" localhost / Student / 1"返回id = 1的学生。我的路线配置:
routes.MapRoute(
name: "StudentID",
url: "Student/{id}",
defaults: new { controller = "Student", action = "Get}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
);
public class StudentController : Controller
{
// GET: Student
[Authorize]
public ActionResult Index()
{
SchoolDbEntities db = new SchoolDbEntities();
return View(db.Students);
}
[Route("Student/{id}")]
[ActionName("Get")]
public ActionResult Get(int id)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.Id == id);
return View(student);
}
}
我配置了路由表并使用路由属性。 但是,当我运行应用程序时,它会抛出一个错误: 无法找到资源。
我如何实现与使用webapi相同的功能。
答案 0 :(得分:2)
如果要在MVC中使用属性路由,则必须在routes.MapMvcAttributeRoutes()
类中调用RouteConfig
来注册它们。
请注意,注册顺序很重要。通过在route.MapMvcAttributeRoutes()
呼叫之前调用routes.MapRoute()
,MVC将查看传统路由之前的属性路由。第一条匹配路线获胜。
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional }
);
在您的控制器中设置属性路由,如下所示:
[RoutePrefix("Student")]
public class StudentController : Controller
{
// GET: Student
[Authorize]
public ActionResult Index()
{
SchoolDbEntities db = new SchoolDbEntities();
return View(db.Students);
}
[Route("{id}")]
public ActionResult Get(int id)
{
SchoolDbEntities db = new SchoolDbEntities();
var student = db.Students.Where(s => s.Id == id);
return View(student);
}
}
这将匹配URL" Student / 1"。