Routing and Url friendly with asp.net mvc

12
How do I make routing and url friendly (dynamically) in my web application using asp.net mvc 5 ?

Currently I have the url:

http://myapp.com/Produto/Details/7

And I want to apply the routing in it so it looks like this:

http://myapp.com/Produto/nome-do-produto

My RouteConfig.cs

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new string[] { "site.Controllers" }
        );
    }
}
    
asked by anonymous 23.08.2015 / 16:24

2 answers

8
  

This question already has an answer , but I could not dial it to close, then I will respond again.

This description after the address is called slug . In this case, what you need to do is a specific route manipulator. For example:

AppStart \ RouteConfig.cs

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Default", action = "Index", id = UrlParameter.Optional }
).RouteHandler = new MeuManipuladorDeRota();

Infrastructure \ MyRotate Handler

public class MeuManipuladorDeRota : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        var url = requestContext.HttpContext.Request.Path.TrimStart('/');

        if (!string.IsNullOrEmpty(url))
        {
            ItemDePagina item = GerenciadorDeRedirecionamento.ObterPaginaPorUrl(url);
            if (item != null)
            {
                MontarRequisicao(item.Controller, 
                    item.Action ?? "Index", 
                    item.ConteudoId .ToString(), 
                    requestContext);
            }
        }

        return base.GetHttpHandler(requestContext);
    }

    private static void MontarRequisicao(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;
    }
}

ViewModels \ ArticlePage.cs

public class ItemDePagina {
    public String Controller { get; set; }
    public String Action { get; set; }
    public int ConteudoId { get; set; }
}

Infrastructure \ Redirection Manager.cs

public static class GerenciadorDeRedirecionamento
{
    public static ItemDePagina ObterPaginaPorUrl(string url)
    {
        ItemDePagina item = null;

        /* Aqui você pesquisa na entidade pela descrição, passando o parâmetro url. */
        /* Este é o ponto mais importante da lógica, que é onde você vai pesquisar o item de acordo com as suas regras de negócio. */
        /* Depois você monta um objeto ItemDePagina (no caso, item) e o devolve. */

        return item;
    }
}
    
25.08.2015 / 18:14
3

AppStart \ RouteConfig.cs

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    routes.MapRoute(
    name: "ProdutoDetalhes",
    url: "produto/{chave}",
    defaults: new { controller = "Produto", action = "Detalhes" },
    constraints: new { chave = @"^[a-zA-Z0-9\-\/_]{2,}$" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}

Controllers / ProductController.cs

public ActionResult Detalhes(string chave)
{
  var produto = db.Produtos.FirstOrDefault(x=>x.chave==chave);
  if (produto==null){
   return HttpNotFound();
  }
  return View(produto);
}
    
28.08.2015 / 23:10