1

Web Api

[HttpGet]
[RequireHttps]
[Route("Api/GetString")]
public string GetString()
{
   return "Worked";
}

RequireHttpsAttribute class

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
            {
                ReasonPhrase = "HTTPS Required"
            };
        }
        else
        {
            var cert = actionContext.Request.GetClientCertificate();
            if (cert == null)
            {
                actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
                {
                    ReasonPhrase = "Client Certificate Required"
                };

            }
            base.OnAuthorization(actionContext);
        }
    }
}

Client (console)

HttpWebRequest client = (HttpWebRequest)WebRequest.Create("https://localhost:44315/api/GetString");
var cert = new X509Certificate2(File.ReadAllBytes(@"C:\ConsoleClient\TestCertificate.pfx"), "password");
client.ClientCertificates.Add(cert);
HttpWebResponse resp = (HttpWebResponse)client.GetResponse();
using (var readStream = new StreamReader(resp.GetResponseStream()))
{
   Console.WriteLine(readStream.ReadToEnd());
}

This https request throws error.

Inner Exception Message : Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
Message : The underlying connection was closed: An unexpected error occurred on a send.

I opened port 443 and tried some settings mentioned in answers of same type of questions but couldn't resolve. Direct access to https://localhost:44315/api/GetString via browser is also not working.

If I change the https to http, it works fine.

Is anything needs to be configured?

Thanks.

Saravanan Sachi
  • 2,572
  • 5
  • 33
  • 42

1 Answers1

0

The solution for me was updating the https protocol from the default ssl3 to tls via https://stackoverflow.com/a/46223433/352432

dabor238
  • 1
  • 1