How can I replace HTTPS with HTTP in a URL? - http

I need to use https on registration pages and http everywhere else. I wrote the following code in global.asax:
protected void Application_BeginRequest(object sender, EventArgs e)
{
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (currentUrl.AbsoluteUri.Contains("Registration"))
{
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}
}
This is working fine for visiting registration pages, but the scheme doesn't switch back to http when I visit other pages.

Please add the following code in Global.asax Page.
protected void Application_BeginRequest(object sender, EventArgs e)
{
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (currentUrl.AbsoluteUri.Contains("Registration"))
{
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = string.IsNullOrEmpty(ConfigurationManager.AppSettings["HttpsPort"].ToString()) ? 443 : Convert.ToInt32(ConfigurationManager.AppSettings["HttpsPort"].ToString());
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}
else if(currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase))
{
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttp;
secureUrlBuilder.Port = 80;
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
}

Related

Redirect is not working with query string parameters in browser on iis after secure https has been set up

I have set iis up so that http redirects to https which is working as it should. The problem is that if I type the url into the browser without http - such as:
example.com/page.aspx?id=1 then it redirects without the parameters - like this:
https://example.com/page.aspx
I am sure that it is some problem in the way iis is redirecting from http to https because if I look in chrome debugger then the url is changed to:
https://example.com/page.aspx
so this happens before my asp.net page is even called.
I have no rewrite rules in my web.config file instead I am using my own class that inherits from IHttpModule:
class LinkModule : IHttpModule
{
string realQueryString = "";
public LinkModule()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
public void Dispose() { }
private void context_BeginRequest(object sender, EventArgs e)
{
HttpRequest request = ((HttpApplication)sender).Request;
HttpContext context = ((HttpApplication)sender).Context;
string applicationPath = request.ApplicationPath;
string requestPath = request.Url.AbsolutePath.Substring(applicationPath.Length);
string path = HttpContext.Current.Request.Path;
//string host = HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
realQueryString = context.Request.QueryString.ToString();
string requesturi = request.Url.AbsoluteUri.Substring(applicationPath.Length);
LoadTemplate(ref requestPath);
context.RewritePath(applicationPath + requestPath);
}
private void LoadTemplate(ref string path)
{
if (path.IndexOf("showproduct.aspx", StringComparison.CurrentCultureIgnoreCase) != -1)
{
path = string.Format("/frontarea/product/index{0}", !string.IsNullOrEmpty(realQueryString) ? "?" + realQueryString : "");
return;
}
}
}

web service is unable to return back to default page

I have asmx web service hosted on IIS and its purpose is to authenticate logined user.
when I run my code using visual studio and debug service is successfully called and authenticate user from DB but it is unable to transfer control back to my code that has default page.
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
Response.Redirect("Default.aspx");
Response.Cache.SetNoStore();
if (!Page.IsPostBack)
{
Session["Uri"] = Request.UrlReferrer;
}
this.hdnLoginStatus.InnerHtml = "";
if (!Page.IsPostBack)
{
new DAS().AuthenticateRequest();
if (HttpContext.Current.Items["LoginStatus"] == null)
return;
var key = (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"];
string msg = (string)GetGlobalResourceObject("Message", key.ToString()) ?? "";
this.ShowMessage(msg, MessageType.Warning);
this.hdnLoginStatus.InnerHtml = "SignedOutForcefully";
}
}
protected void LoginUser_LoggedIn(object sender, EventArgs e)
{
Response.Redirect("Default.aspx?key=" + (AuthWS.LoginStatus)HttpContext.Current.Items["LoginStatus"]);
}

Sending information in url parameters using XmlHttpRequest in get method, how do i retrieve those parameters in aspx page?

I want to retrieve those two parameters which are passed in url
// Read the text file with an XMLHttpRequest
var xh;
if (window.XMLHttpRequest) {
xh = new XMLHttpRequest();
alert("Object created");
}
alert(xh);
xh.onreadystatechange = function() {
if (xh.readyState == 4 && xh.status == 200) {
alert(xh.responseText);
document.getElementById("d1").innerHTML = xh.responseText;
}
}
xh.open("GET", "Default.aspx?name=Henry&lname=Ford"", true);
xh.send();
</script>
Now i want to retrieve those two parameters in aspx page.
Code in aspx page-
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(DateTime.Now);
}
}
You need to get that using QueryString as GET this is get request , params are passed using QueryString. For this url , you have to use following for in page_load to retrive.
//Default.aspx?name=Henry&lname=Ford
protected void Page_Load(object sender, EventArgs e)
{
string name,lname;
if(Request.QueryString["name"]!=null)
name = Request.QueryString["name"].ToString();
if (Request.QueryString["lname"] != null)
lname = Request.QueryString["lname"];
}

HTTP module re-writing the URL with some encryption

I am writing one class with the help of HTTPModule to check userIdentity in session before he access any page.If the variable in the session is null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx", false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of encryption in URL for which my Breadcrumbs are not working in the page. The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu

Secure webApplication

I am building an application(asp.net) with online payment so i want to make these payment page SSL enable. How can i do that..
Help me..
Thanks
Create class similar to
public class SecurePage : Page
{
protected override void OnInit( EventArgs e )
{
//retrieve appsettings value. set to false for localhost or dev environment
var sslRequired = bool.Parse(WebConfigurationManager.AppSettings["Security-SSL-Required"] ?? "true");
var currentUrl = System.Web.HttpContext.Current.Request.Url;
if (!currentUrl.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase) && sslRequired)
{
//build the secure uri
var secureUrlBuilder = new UriBuilder(currentUrl);
secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
//use the default port.
secureUrlBuilder.Port = -1;
//redirect and end the response.
System.Web.HttpContext.Current.Response.Redirect(secureUrlBuilder.Uri.ToString());
}
base.OnInit(e);
}
}
Then for pages that require SSL inherit from this base class:
public class Login : SecurePage
{
protected void Page_Load
(
object sender,
EventArgs e )
{
}
}

Resources