Router and URL-friendly with Asp.net mvc

Asked

Viewed 2,381 times

12

How I Route 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 route 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" }
        );
    }
}
  • Check if it helps you http://answall.com/questions/66896/configurar-rotas-usando-areas-em-asp-net-mvc-5

2 answers

8


This question already has an answer, but I couldn’t schedule to close, so I’ll reply again.

This description that stands after the address is called Slug. In this case, what you need to do is a specific route handler. For example:

Appstart Routeconfig.Cs

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

Infrastructure Meumanipuladorderota.Cs

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 Itemdepagina.Cs

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

Managed Infrastructure redirection.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;
    }
}

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/Productocontroller.Cs

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.