asp.net-mvc - 如何仅为登录和特定页面 MVC 激活 SSL

标签 asp.net-mvc asp.net-mvc-4 ssl https forms-authentication

我有一个 MVC 4 Web 应用程序,我需要 SSL 来执行一组特定的操作,现在我希望登录过程也受 SSL 保护。

设置好所有内容后,由于登录页面的 redirectToUrl 参数未指定模式,所有需要登录的页面都被重定向到 https,无论 [RequireHttps] 属性如何我已经设置(或者更确切地说未设置)操作。

由于我没有使用 RequireHttps 属性修饰的页面托管混合内容,这会触发通常的浏览器警告,这会让用户感到困惑,我想避免。

有没有办法解决这个问题?我想从登录操作中获取架构,但除了 returnUrl 参数之外我找不到对原始请求的引用,它只是一个相对路径。

我在 SO 中找到的引用是 creating a custom attribute装饰每个不需要 https 的 Action,但还有比这更 DRY 的东西吗?

最佳答案

我发现以下有用,而不是用 [RequireHttps] 装饰,我用 [Secure] 装饰,然后这个属性为我工作。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MyNameSpace.Attributes
{
    public class SecureAttribute : ActionFilterAttribute
    {
        #region Variables and Properties
        public bool PermanentRedirect { get; set; }
        #endregion

        #region Public Methods
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Cache for efficiency
            var request = filterContext.HttpContext.Request;
            var response = filterContext.HttpContext.Response;

            // Make sure we're not in https or local
            if (!request.IsSecureConnection)
            {
                string redirectUrl = request.Url.ToString().Replace(
                    Uri.UriSchemeHttp,
                    Uri.UriSchemeHttps);

                if (PermanentRedirect)
                {
                    // Set the status code and text description to redirect permanently
                    response.StatusCode = 301;
                    response.StatusDescription = "Moved Permanently";
                }
                else
                {
                    // Set the status code and text description to redirect temporary (found)
                    response.StatusCode = 302;
                    response.StatusDescription = "Found";
                }

                // Add the location header to do the redirect
                response.AddHeader("Location", redirectUrl);
            }

            base.OnActionExecuting(filterContext);
        }
        #endregion
    }
}

关于asp.net-mvc - 如何仅为登录和特定页面 MVC 激活 SSL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10772922/

相关文章:

c# - @Html.Value of(x=>x.Property Name) 和@Model.Property Name 有什么区别

ssl - AWS S3.NET 开发工具包

c# - 如何为 .NET Core View 类替换 Request.Url.GetLeftPart(UriPartial.Authority)?

asp.net-mvc - 是否有一个 log4net 附加程序用于生成管理员查看页面?

asp.net-mvc - 在 Controller 级别指定操作过滤器与在操作方法级别指定操作过滤器,后者将首先运行

.net - 如何将我的 HTTP 处理程序用于选定的路径,并将 MVC 处理程序用于其余路径?

c# - ASP.NET MVC - 默认范围验证错误消息未被覆盖

entity-framework - LINQ to Entities 无法识别方法 - Include + Where

mysql - 如何通过 SSL 设置 ColdFusion MySQL 数据源?

ssl - 如何在新的 Apache Http Client 4.3 中创建 SSL 套接字工厂?