"{controller}/{action}/{id}", new { controller = "Default", action = "Index", id = UrlParameter.Optional }
) assumes default values, therefore when accessing www.site.com/helloworld will try to throw us on the helloworld controller in the Action Index. routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Default", action = "Index", id = UrlParameter.Optional } ).RouteHandler = new FriendlyUrlRouteHandler();
public class FriendlyUrlRouteHandler : MvcRouteHandler { private static readonly Regex TypicalLink = new Regex("^.+/.+(/.*)?"); protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { // Path www.site.com/helloworld?id=1 /helloworld // var url = requestContext.HttpContext.Request.Path.TrimStart('/'); if (!string.IsNullOrEmpty(url) && !TypicalLink.IsMatch(url)) { PageItem page = RedirectManager.GetPageByFriendlyUrl(url); if (page != null) { FillRequest(page.ControllerName, page.ActionName ?? "GetStatic", page.ID.ToString(), requestContext); } } return base.GetHttpHandler(requestContext); } /// <summary> request- , </summary> private static void FillRequest(string controller, string action, string id, RequestContext requestContext) { if (requestContext == null) { throw new ArgumentNullException("requestContext"); } requestContext.RouteData.Values["controller"] = controller; requestContext.RouteData.Values["action"] = action; requestContext.RouteData.Values["id"] = id; } }
public abstract class BaseController : Controller { /// <summary> </summary> public virtual ActionResult GetStatic(int id) { return HttpNotFound(); } }
public static class RedirectManager { public static PageItem GetPageByFriendlyUrl(string friendlyUrl) { PageItem page = null; using (var cmd = new SqlCommand()) { cmd.Connection = new SqlConnection(/*YourConnectionString*/); cmd.CommandText = "select * from FriendlyUrl where FriendlyUrl = @FriendlyUrl"; cmd.Parameters.Add("@FriendlyUrl", SqlDbType.NVarChar).Value = friendlyUrl.TrimEnd('/'); cmd.Connection.Open(); using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (reader.Read()) { page = new PageItem { ID = (int) reader["Id"], ControllerName = (string) reader["ControllerName"], ActionName = (string) reader["ActionName"], FriendlyUrl = (string) reader["FriendlyUrl"], }; } } return page; } } }
Source: https://habr.com/ru/post/132799/
All Articles