ExpressionBuilder for SSL Redirects

In this post I explained why you have to use absolute URLs when you switch to SSL. I showed the GetAbsoluteUrl method which allows to pass in a relative URL and a protocol and returns an absolute URL. By using the <% %> notation, you can also directly subsitute links in HTML markup, e.g.

<a href=”<%= SslTools.GetAbsoluteUrl(“~/ssl/default.aspx”, ProtocolOptions.Https) %>“>SSL Page</a>

This works only for literals like HTML. If you want to set attributes of ASP.NET controls inline, you have to use an expression builder (read more here). This allows this syntax:

<asp:HyperLink runat=”server” ID=”_lnk” Text=”SSL Page” NavigateUrl=”<%$ HttpsUrl:~/ssl/default.aspx %> />

The ExpressionBuilder mostly consists of boiler plate code that is used to inject a call to GetValue into the compiled ASP.NET page. GetValue then just calls the GetAbsoluteUrl method I showed in my earlier post.

public class HttpsUrl : ExpressionBuilder

{

    public override CodeExpression GetCodeExpression(

      BoundPropertyEntry entry,

      object parsedData,

      ExpressionBuilderContext context)

    {

        // boilerplate code to inject ‘GetValue’ in the page class

        CodeTypeReferenceExpression targetClass = new

          CodeTypeReferenceExpression(typeof(HttpsUrl));

        string targetMethod = “GetValue”;

        CodeExpression methodParameter = new

          CodePrimitiveExpression(entry.Expression.Trim());

 

        return new

          CodeMethodInvokeExpression(

            targetClass, targetMethod, methodParameter);

    }

 

    public static object GetValue(string param)

    {

        return SslTools.GetAbsoluteUrl(param, ProtocolOptions.Https);

    }

}

ExpressionBuilders have to be registered in the compilation element in web.config:

<compilation debug=false>

  <expressionBuilders>

    <add expressionPrefix=HttpsUrl type=HttpsUrl, App_Code />

  </expressionBuilders>

</compilation>

 

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s