-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRequireHttpsAttribute.cs
39 lines (35 loc) · 1.66 KB
/
RequireHttpsAttribute.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class RequireHttpsAttribute : ActionFilterAttribute
{
public bool RequireSecure = false;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var httpsPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpsPort"]);
var httpPort = Convert.ToInt32(ConfigurationManager.AppSettings["httpPort"]);
var request = filterContext.HttpContext.Request;
var response = filterContext.HttpContext.Response;
if (httpsPort > 0 && RequireSecure)
{
string url = null;
if (httpsPort > 0)
{
url = "https://" + request.Url.Host + request.RawUrl;
if (httpsPort != 443)
{
var builder = new UriBuilder(url) { Port = httpsPort };
url = builder.Uri.ToString();
}
}
if (httpsPort != request.Url.Port)
{
filterContext.Result = new RedirectResult(url);
}
}
// se for uma conexao segura e não está requerendo um SSL, retira o ssl e volta para http.
else if (filterContext.HttpContext.Request.IsSecureConnection && !RequireSecure)
{
filterContext.Result = new RedirectResult(filterContext.HttpContext.Request.Url.ToString().Replace("https:", "http:").Replace(httpsPort.ToString(), httpPort.ToString()));
filterContext.Result.ExecuteResult(filterContext);
}
base.OnActionExecuting(filterContext);
}
}