首先,在ASP.NET MVC应用程序的RouteConfig.cs文件中定义路由规则。例如,以下路由规则会将请求路由到名为MyFunction的控制器的Index方法:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "MyRoute",
url: "my/{myparameter}",
defaults: new { controller = "MyController", action = "Index" }
);
// Default Route
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
接下来,在控制器中编写处理请求的函数。例如,以下函数会从URL参数中读取myparameter值,并根据其是否等于"hello"显示不同视图:
public class MyController : Controller
{
public ActionResult Index(string myparameter)
{
if (myparameter == "hello")
{
return View("HelloView");
}
else
{
return View("OtherView");
}
}
}
最后,在Views文件夹中创建HelloView.cshtml和OtherView.cshtml视图文件,这些文件将根据控制器函数的返回值进行渲染。
Hello, World!
Other View