sábado, 29 de septiembre de 2012

Reescribir URLs en ASP.NET con URLRewriter.NET

Reescribir URL's tiene muchos beneficios, listare los principales:
  1. Apariencia SEO amigable

  2. URLs seguras

  3. No necesitamos cambiar el bookmark con cambios en su estructura

Antes de reescribir la URL my URL se veia asi: http://localhost:2661/URLRewrite2/DynamicPage.aspx?MyTitleId=1 Despues de reescribir la URL la URL se ve asi http://localhost:2661/URLRewrite2/Article/Asp-Net-website-paths-1.aspx Vamos a reescribir la URL con un simple ejemplo Este sitio web mostrara una lista de articulos en un GridView y al seleccionar uno de ellos, mostrara dinamicamente el contenido del articulo generado. Antes de reescribir la URL cuando tu pongas el mouse sobre el primer link del articulo "ASP.NET Ruta del Website" usamos el query string para mostrar el contenido del articulo.
La pagina dinamica muestra el QueryString, antes de reescribir la URL.
Despues de reescribir la URL lograremos una URL amigable la cual nos mostrara el contenido de los articulos.
Para este ejemplo crearemos una base de datos llamada Articletable. Despues crearemos una tabla llamada Articletable la cual tendra los campos ID, titulo, descripcion y nombre de autor. El titulo del link sera creado en el control GridView de ASP.NET. Cuando demos click en el titulo del link nos redigira a la pagina dinamica. El script para crear la tabla sera el siguiente:
CREATE TABLE [dbo].[Articletable](
      [ID] [int] NOT NULL,
      [Title] [varchar](200) NULL,
      [Description] [varchar](400) NULL,
      [Author] [varchar](50) NULL
)
Insertamos datos en esta tabla
INSERT INTO Articletable VALUES(1,'How to validate dropdownlist in asp.net','Here, we will learn how to validate a DropDownList in ASP.NET.','Rohatash Kumar');
GO
INSERT INTO Articletable VALUES(2,'Introduction to .NET Assemblies in VB.NET',' Here is a comprehensive introduction to .NET assemblies.','sunil Kumar');
go
INSERT INTO Articletable VALUES(3,'BinaryReader and BinaryWriter classes in VB.NET','In this article I will explain about BinaryReader and BinaryWriter Classes in VB.NET.','Deepak Kumar');
 
go
INSERT INTO Articletable VALUES(4,'StreamWriter class in VB.NET','This article shows how to create a new text file and write a string to it.','Rohatash Kumar');
go
Ahora en ASP.NET Paso 1: Descargamos los archivos binarios para URLRewriter.NET(Inteligencia.URLRewriter.dll) Paso 2: Agregamos una referencia a esos archivos binarios, damos click derecho y agregamos referencia.
Paso 3: Creamos 2 paginas .aspx llamadas Default.aspx y DynamicPage.aspx Paso 4: Actualizamos el archivo Web.config para hacer que el URLRewriter funcione.
<configuration>

<configSections>
<section name="rewriter"
requirePermission="false"
type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
</configSections>

<system.web>

<httpModules>
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
</httpModules>

</system.web>

<system.webServer>

<modules runAllManagedModulesForAllRequests="true">
<add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule" />
</modules>

<validation validateIntegratedModeConfiguration="false" />

</system.webServer>

<rewriter>
<rewrite url="~/Article/(.+)-(.+).aspx" to="~/DynamicPage.aspx?MyTitleId=$2"/>
</rewriter>

</configuration>
Paso 5: En el Default.aspx agregamos el GridView que lucira asi:
agregamos este codigo en la ventana de codigo:
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <h1>
            <span style="color: #009900">After URL Rewriting</span></h1>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" Width="788px">
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <Columns>
                <asp:TemplateField HeaderText="Title">
                    <ItemTemplate>
                        <asp:HyperLink ID="hlTitle" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Title")%>' NavigateUrl='<%#GenerateURL(DataBinder.Eval(Container.DataItem,"Title"),DataBinder.Eval(Container.DataItem,"Id"))%>'></asp:HyperLink>                        
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Description">
                    <ItemTemplate>
                        <asp:Label ID="lblDesc" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"Description")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
        </asp:GridView>
         
    </div>
    </form>
</body>
Y este sera el codigo .cs
protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = GetData();
        GridView1.DataBind();
    }

    //public static string GenerateURL(object Title, object strId)
    //{
    //    string strTitle = Title.ToString();

    //    strTitle = "~/DynamicPage.aspx?MyTitleId=" + strId;

    //    return strTitle;
    //}

    public static string GenerateURL(object Title, object strId)
    {
        string strTitle = Title.ToString();

        #region Generate SEO Friendly URL based on Title
        //Trim Start and End Spaces.
        strTitle = strTitle.Trim();

        //Trim "-" Hyphen
        strTitle = strTitle.Trim('-');

        strTitle = strTitle.ToLower();
        char[] chars = @"$%#@!*?;:~`+=()[]{}|\'<>,/^&"".".ToCharArray();
        strTitle = strTitle.Replace("c#", "C-Sharp");
        strTitle = strTitle.Replace("vb.net", "VB-Net");
        strTitle = strTitle.Replace("asp.net", "Asp-Net");

        //Replace . with - hyphen
        strTitle = strTitle.Replace(".", "-");

        //Replace Special-Characters
        for (int i = 0; i < chars.Length; i++)
        {
            string strChar = chars.GetValue(i).ToString();
            if (strTitle.Contains(strChar))
            {
                strTitle = strTitle.Replace(strChar, string.Empty);
            }
        }

        //Replace all spaces with one "-" hyphen
        strTitle = strTitle.Replace(" ", "-");

        //Replace multiple "-" hyphen with single "-" hyphen.
        strTitle = strTitle.Replace("--", "-");
        strTitle = strTitle.Replace("---", "-");
        strTitle = strTitle.Replace("----", "-");
        strTitle = strTitle.Replace("-----", "-");
        strTitle = strTitle.Replace("----", "-");
        strTitle = strTitle.Replace("---", "-");
        strTitle = strTitle.Replace("--", "-");

        //Run the code again...
        //Trim Start and End Spaces.
        strTitle = strTitle.Trim();

        //Trim "-" Hyphen
        strTitle = strTitle.Trim('-');
        #endregion

        //Append ID at the end of SEO Friendly URL
        strTitle = "~/Article/" + strTitle + "-" + strId + ".aspx";

        return strTitle;
    }

    private DataTable GetData()
    {
        string strConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
        SqlConnection conn = new SqlConnection(strConn);
        SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description from Articletable", conn);
        DataSet ds = new DataSet();
        da.Fill(ds, "Articletable");
        return ds.Tables["Articletable"];
    }
Olvide decirles crean una cadena de conexion en el Webconfig.
 <connectionStrings>
  <add name="connStr" connectionString="Data Source=XSaint;Initial Catalog=Articletable;Integrated Security=SSPI"/>
 </connectionStrings>
Ahora vamos a la segunda pagina DynamicPage.aspx El webform se vera asi:
El codigo ASP.NET para la pagina sera el siguiente:
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h1><img src="../Images/article.gif" />Article</h1>
        <b>Title:</b><asp:Label ID="lblTitle" runat="server" Text="Label" Font-Bold="true" ForeColor="blue"></asp:Label><br /><br />
        <b>Author:</b><asp:Label ID="lblauthor" runat="server" Text="Label" Font-Bold="true" ForeColor="blue"></asp:Label><br /><br />
        <b>Description:</b><br />
        <asp:Label ID="lblDescription" runat="server" Text="Label"></asp:Label><br /><br />
        <asp:Button ID="Button1" runat="server" Text="Make PAGE POSTBACK"/><br /><br />
        <a href="javascript:history.go(-1)">Back</a>
    </div>        
    </form>
</body>
Y el codigo .cs sera el siguiente:
protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["MyTitleId"] != null)
        {
            string strId = Request.QueryString["MyTitleId"].ToString();
            DisplayArticle(strId);    
        }
    }

    private void DisplayArticle(string strId)
    {     
        string strConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
        SqlConnection conn = new SqlConnection(strConn);
        SqlDataAdapter da = new SqlDataAdapter("select Id,Title,Description,author from Articletable where Id=" + strId, conn);
        DataSet ds = new DataSet();
        da.Fill(ds, "Articletable");
        lblTitle.Text = ds.Tables["Articletable"].Rows[0][1].ToString();
        lblDescription.Text = ds.Tables["Articletable"].Rows[0][2].ToString();
        lblauthor.Text = ds.Tables["Articletable"].Rows[0][3].ToString();  
    }
Si ghubiese algun error diganme para ayudrles, pero con el codigo que puse debe estar ejecutandose como en la figura de arriba. Espero les sirva el codigo.

0 comentarios:

Publicar un comentario