admin管理员组文章数量:1516870
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
版权声明:本文标题:从HTTP到HTTPS:MVC项目的安全转型之路 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.betaflare.com/biancheng/1771528812a3266548.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。


发表评论