getting https to work locally in asp.net MVC4 application - asp.net

I followed this tutorial exactly:
http://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx
But when I am running locally and try to navigate from a non-https page (like home/index) to and a page I decorated with [RequireHttps] I get the generic "SSL connection error" message.
I hate posting such a generic question, but can you think of anything I have missed? It is a large asp.net mvc4 application, I enabled ssl in the project, it shows the ssl url. Navigating to the ssl url manually does not work either.
HALP!
NOTE: Using IIS Express with visual studio 2012
Per the comment, the error I am getting is Cannot Establish SSL connection.

You shouldn't be using Https when testing locally. I've created my own Https Filter where it will ignore all the local traffic in the localhost and only works either on staging and live environment. You can modify the code to suit you need.
public class RequireSSLAttribute : FilterAttribute, IAuthorizationFilter {
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if(filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if(!filterContext.HttpContext.Request.IsSecureConnection) {
HandleNonHttpsRequest(filterContext);
}
}
protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext) {
if(filterContext.HttpContext.Request.Url.Host.Contains("localhost")) return;
if(!String.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) {
throw new InvalidOperationException("The requested resource can only be accessed via SSL");
}
string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
//ignore if the request is from a child action
if(!filterContext.IsChildAction) {
filterContext.Result = new RedirectResult(url);
}
}
}
And this is how you use it...
[RequireSSL(Order=1), Authorize(Order=2)]
public PartialViewResult AccountHeader() {
blah...blah...
}

I know it's already answered, but I thought I'd point out the cause of the original error, which the other answers omit.
When you enable SSL on IIS Express, your site is hosted on 2 ports, 1 for http and another for https. When you debug in Visual Studio, the port is usually specified explicitly. The links on your site probably don't specify port numbers, so when you link from a plain http page to a https one, the port number won't change, and you'll request a https page on the plain http port. This is why you get the SSL connection error.
On a real server the port numbers should be implicit, so the problem shouldn't come up, but you'll need to make sure you're using the right port when debugging locally.

You need to add ssl certificate to your site instance in IIS.
To create certifiacte and add it to IIS7 try this tutorial: http://technet.microsoft.com/en-us/library/cc753127(v=ws.10).aspx
After creation you'll be able to add it to your website. Open in IIS 'your website' -> Bindings -> Add and add new host header. Select https, port 443 and select created sertificate.

Related

https returns 404 while http works fine

I'm trying to configure HTTPS for my application and it's returning "HTTP Error 404. The requested resource is not found.", but the resource actually exists.
I've done several tests regarding this problem and here's a list:
Access via HTTP works perfectly.
I created a simple HTML file to try to access via HTTPS (https://example.com/myfile.html) and it also worked (which leads to the understanding that the problem is in something in my application).
Setting binding security mode to "Transport" in WebConfig file.
Port 443 for HTTPS is fine
PS.: When I try to access the site by HTTPS, by a route and resource that REALLY exists (for example "https://example.com/login.aspx") it returns 404 and recognizes the site as not secure (or i.e. it doesn't recognize the certificate in the route, maybe because it redirects me to http). But, if I try to access a resource that DOES NOT exist, like "https://example.com/Testlogin.aspx", it returns 404 but with a different message (comparisons attached) and recognizes the site as secure (HTTPS).
It's a C# webforms application with aspx, and I'm trying to set it up on IIS server.
Solved!
After many tests and running out of alternatives, I decided to investigate whether there was something in the source code that prevented the application from accessing HTTPS. Behold, I finally found the problem: in the application there was the following method that was redirecting the application to HTTP. I just needed to change the call parameter to true and it worked.
public void protocoloSeguro(bool bSeguro)
{
string redirectUrl = null;
if (bSeguro && !Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("http:", "https:");
else
if (!bSeguro && Request.IsSecureConnection) redirectUrl = Request.Url.ToString().Replace("https:", "http:");
if (redirectUrl != null)
Response.Redirect(redirectUrl);
}

Visual Studio 2013 WebTest Request Failed: An existing connection was forcibly closed by the remote host

I'm attempting to run a Visual Studio 2013 web test on my local machine. This is a test that I've run successfully (the last time about 2 months ago). The first step in the web test is a GET request to a login page. It looks like this:
GET https://example.com/Login.aspx
When I type this url into a web browser it succeeds. Also, I can successfully record a web test where I merely navigate to this page and log in. But when I attempt to re-run the webtest that I just recorded I get this response to the GET request:
Request failed: An existing connection was forcibly closed by the remote host
Nothing is logged by IIS on example.com (IIS does not log the GET request). But, when I manually log in, or when I record the web test, IIS does log the GET request properly.
There are no messages logged in the event viewer on example.com or on my local host.
Any suggestions on how to debug this issue are much appreciated.
For me, the problem was a TLS handshake. Solved by adding a plug-in to web test.
Think is original question, that helps me: https://social.msdn.microsoft.com/Forums/vstudio/en-US/bc3ebf23-575d-4e54-bd6b-a1ed87fe5213/web-performance-test-is-not-working-with-tls12-enabled?forum=vstest
Plugin source:
using System;
using System.ComponentModel;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using Microsoft.VisualStudio.TestTools.WebTesting;
[Description("This plugin will force the underlying System.Net ServicePointManager to negotiate downlevel SSLv3 instead of TLS. WARNING: The servers X509 Certificate will be ignored as part of this process, so verify that you are testing the correct system.")]
public class TLSPlugin : WebTestPlugin
{
[Description("Enable or Disable the plugin functionality")]
[DefaultValue(true)]
public bool Enabled { get; set; }
public override void PreWebTest(object sender, PreWebTestEventArgs e)
{
base.PreWebTest(sender, e);
//For TLS
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//For SSL
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//we wire up the callback so we can override behavior and force it to accept the cert
ServicePointManager.ServerCertificateValidationCallback = RemoteCertificateValidationCB;
//let them know we made changes to the service point manager
e.WebTest.AddCommentToResult(this.ToString() + " has made the following modification-> ServicePointManager.SecurityProtocol set to use SSLv3 in WebTest Plugin.");
}
public static bool RemoteCertificateValidationCB(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
//If it is really important, validate the certificate issuer here.
//this will accept any certificate
return true;
}
}
Today I faced a similar problem with Visual Studio 2017 Enterprise and after a couple of hours, able to resolve it.
I added below two registry keys in my machine where Visual Studio is installed and it resolved the issue.
For a complete description of setting, Refer documentation:-
https://support.microsoft.com/en-in/help/4040243/how-to-enable-tls-1-2-for-configuration-manager
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001
Two entries of SchUseStrongCrypto key needs to be done in the registry just like below snapshot.
Visual Studio 2019 - Load Test
Scenario: Using unit test for the load test.
Problem: When running the unit test manually it runs without problems. As soon as the load test starts it fails with same error: "An existing connection was forcibly closed by the remote host".
Solution: Force TLS1.2 when initializing the unit test.
[TestInitialize]
public void Init()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}

subdomain url redirects to the main url

I developed a website in asp.net and hosted on windows server which does not provide me the wild card entry for the subdomain name. How can I write my url as e.g
http://subdomainName.DomainName.org?
I want to redirect the url with a subdomain to the main domain; so url "subdomainName.DomainName.org" should redirect to "DomainName.org", where my subdomain name is not fixed. The subdomain will be assigned to each user.
How can I achieve this?
The subdomain is part of the DNS server, and work together with the IIS setup.
So, you can NOT change the DNS setup from asp.net, neither the IIS setup. When a provider gives your the access to add extra sub-domains, what is actually do is that create new entries on the DNS entry, and then add map that to the IIS, so that sub-domains to look at your site. If your provider did not have give you a tool to add sub-domains, nether you can edit the DNS entries, then you can NOT add them from asp.net.
If you can add sub-domains then you can manipulate what you going to server and show on global.asax at Application_BeginRequest using the redirect or the Rewrite the path. For example:
protected void Application_BeginRequest(Object sender, EventArgs e)
{
var SubDomain = GetSubDomain(HttpContext.Current.Request.Url.Host);
if(!String.IsNullOrEmpty(SubDomain) && SubDomain != "www")
{
Response.Redirect("www.yourdomain.com", true);
return;
}
}
// from : http://madskristensen.net/post/Retrieve-the-subdomain-from-a-URL-in-C.aspx
private static string GetSubDomain(Uri url)
{
string host = url.Host;
if (host.Split('.').Length > 1)
{
int index = host.IndexOf(".");
return host.Substring(0, index);
}
return null;
}
Similar posts:
How to remap all the request to a specific domain to subdirectory in ASP.NET
Redirect Web Page Requests to a Default Sub Folder
How to refer to main domain without hard-coding its name?
Retrieve the subdomain from a URL in C#

HTTP to HTTPS redirection in asp.net not working

We have a simple requirement to use https for certain specific pages in a asp.net 4.0 web application. For checking our implementation, we deployed a simple asp.net 4.0 app to IIS 7. The app has been coded to redirect the default.aspx page to securepage.aspx over https based on a web.config flag.
protected void Page_Load(object sender, EventArgs e)
{
Uri requestUri = Page.Request.Url;
UriBuilder builder = new UriBuilder("https", requestUri.Host, requestUri.Port, "SecurePage.aspx");
string secureUrl = builder.Uri.ToString();
if (bool.Parse(ConfigurationManager.AppSettings["UseSecure"]))
{
Response.Redirect(secureUrl, true);
}
else
{
Response.Write(secureUrl);
}
}
But after we deploy this app on IIS 7 and load the default.aspx page, it shows "Internet Explorer cannot display the webpage". But if we turn the config flag off, it displays the page properly. The app has http binding on port 82 and https on port 444.
Can anybody point me in where we are going wrong.
When you type in front https then the browser is go on port 443 and not on 444, so to movit on your custom port you need to type it as.
UriBuilder builder = new UriBuilder("http", requestUri.Host, 444, "SecurePage.aspx");
You are using the current request's port via requestUri.Port, which returns 80. You should hard-code the 444 instead:
UriBuilder builder = new UriBuilder("https", requestUri.Host, 444, "SecurePage.aspx");
Or use a configurable variable if the port changes.

Request.ServerVariables["SERVER_NAME"] is always localhost

I'm developing an ASP.NET 3.5 application with Visual Studio 2008.
My default page has some redirection code in the Page_Load method:
protected void Page_Load(object sender, EventArgs e)
{
string sname = Request.ServerVariables["SERVER_NAME"].ToLower();
if (sname.ToLower().Contains("intranet"))
{
Response.Redirect("/intranet/Default.aspx");
}
else if ((sname.ToLower().Contains("extranet")))
{
Response.Redirect("/extranet/Default.aspx");
}
else {
Response.Redirect("/web/Default.aspx");
}
}
I've modified my hosts file so that intranet and extranet redirect to my local machine.
127.0.0.1 intranet
127.0.0.1 extranet
I then type the URL http://extranet in my browser.
However, the problem is that the server variable value returned from Request.ServerVariables["SERVER_NAME"] is always "localhost" and not "extranet"
Any help on how to get the right value?
Many thanks
Request.ServerVariables["HTTP_HOST"] gets the value I was looking for :)
Youre right
You want to retrieve the full address of the website that the request came to. Do not use "SERVER_NAME", use "HTTP_HOST".
Read here,
http://www.requestservervariables.com/get-address-for-website
Server_Name returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs
Why don't you use Request.URL?
Your host files only redirect the requests to a specific IP address - you cannot change the requesting machines name by editing them.

Resources