Pregunta

How do I ensure a page in my site is ALWAYS served securely?

I've been doing some investigation, and it looks like I can use the following class:

HttpContext.Current.Request.IsSecureConnection;

Firstly, is this the correct way to do it? If so, how do I use that class? do I use it to set a bool, and perform a redirect on it if that fails?

I've checked out this link, but I don't know how to convert this to be used with WebPages?

ASP.net check if page is http or https

¿Fue útil?

Solución

Rather than writing code to perform this, I would suggest using the URL Rewrite component within IIS on the server you're hosting it on (if present). URL Rewrite will be able to catch the requests and rewrite them as secure before your code ever sees the request.

If you need help setting up URL rewrite there is information at the following link, including what your web.config should end up looking like:

http://www.jppinto.com/2010/03/automatically-redirect-http-requests-to-https-on-iis7-using-url-rewrite-2-0/


To also directly answer your question, IsSecureConnection is a read-only bool property that tells you whether you are running on a secure connection. You can use it in any of your .cshtml pages from the Request object. Just add the following to a page to get the idea:

@Request.IsSecureConnection

To set the connection as secure you would need to redirect the user to a https connection, but as I said above I feel this is better achieved with URL Rewrite than through code (although your code can certainly ensure that it is on a secure connection when it expects to be and throw an error if it isn't).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top