日期:2010-02-28  浏览次数:20461 次

  1 using System.Web.Mvc;
 2 
 3 namespace Snowdream.Demo.RequireHttps
 4 {
 5     public class RequireHttpsAttribute:AuthorizeAttribute
 6     {
 7         /// <summary>
 8         /// 重写OnAuthorization方法
 9         /// </summary>
10         /// <param name="filterContext"></param>
11         public override void OnAuthorization(AuthorizationContext filterContext)
12         {
13             // 如果已经是https连接则不处理,否则重定向到https连接
14             if (!filterContext.HttpContext.Request.IsSecureConnection)
15             {
16                 // 获取当前请求的Path
17                 string path = filterContext.HttpContext.Request.Path;
18 
19                 // 从web.config中获取host,也可以直接从httpContext中获取
20                 string host = System.Configuration.ConfigurationManager.AppSettings["HostName"];
21 
22                 // 从web.config中获取https的端口
23                 string port = System.Configuration.ConfigurationManager.AppSettings["HttpsPort"];
24 
25                 // 如果端口号为空表示使用默认端口,否则将host写成host:port的形式
26                 if (port != null)
27                 {
28                     host = string.Format("{0}:{1}", host, port);
29                 }
30 
31                 // 重定向到https连接
32                 filterContext.HttpContext.Response.Redirect(string.Format("https://{0}{1}", host, path));
33             }
34         }
35     }
36 }
37 


由于https和https服务使用不同的端口号,而且https不能绑定主机头,只能通过不同端口的方式来区分各个站点,所以这里将host和port信息写到了web.config里,以方便配置。在web.config的appsettings节加入如下信息即可