在ASP.NET MVC中,设置RESTful URL需要通过路由配置。以下是一个完整的答案,涵盖了名词概念、分类、优势、应用场景、推荐的腾讯云相关产品和产品介绍链接地址。
要使用ASP.NET MVC路由设置RESTful URL,您需要遵循以下步骤:
Microsoft.AspNet.Mvc
包。App_Start
文件夹中创建一个名为RouteConfig.cs
的文件,并添加以下代码:using System.Web.Mvc;
using System.Web.Routing;
public class RouteConfig
{
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 }
);
}
}
Global.asax.cs
文件中,调用RouteConfig.RegisterRoutes(RouteTable.Routes)
方法:using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
using System.Web.Mvc;
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
return View();
}
// GET: Product/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Product/Create
public ActionResult Create()
{
return View();
}
// POST: Product/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Product/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Product/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
现在,您已经成功设置了RESTful URL。您可以通过以下方式访问这些URL:
/Product
/Product/Details/5
/Product/Create
/Product/Edit/5
/Product/Delete/5
领取专属 10元无门槛券
手把手带您无忧上云