Tuesday, July 8, 2014

Problem using context in global.asax file asp.net iis7

 <%@ Application CodeBehind="Global.asax.cs" Language="C#" %>

<script RunAt="server">
    public void Application_Start()
    {
        string str = Context.Request.Url.AbsoluteUri.Replace("http", "https");
        Context.RewritePath(str);
    }
</script>
Error will like this:
"Request is not available in this context"
 Now Just modify code like bellow in Global.asax
 
The main reason is that the RewritePath is not working because the http and https are working on different port. Also the Application Start is not the place to call this thinks. The BeginRequest is the one. 
protected void Application_BeginRequest(Object sender, EventArgs e)
{
    HttpApplication app = (HttpApplication)sender;
    string cTheFile = HttpContext.Current.Request.Path;
    string sExtentionOfThisFile = System.IO.Path.GetExtension(cTheFile);
    if (sExtentionOfThisFile.Equals(".aspx", StringComparison.InvariantCultureIgnoreCase))
    {
        if (!app.Context.Request.IsSecureConnection)
        {
            Response.Redirect(app.Context.Request.RawUrl.Replace("http://", "https://"), true);
            return;
        }
    }

    // rest of your code here and below
} 
 
it's working 100%.. 
 

No comments:

Post a Comment

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...