admin 管理员组

文章数量: 1184232

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("", host, path));
33             }
34         }
35     }
36 }
37

本文标签: 连接 新手指南 编程