我有一个 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/