MVC RequireHttps如果没有HTTPS重定向 [英] MVC RequireHttps and redirect if not https

查看:891
本文介绍了MVC RequireHttps如果没有HTTPS重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过许多THRU在ASP.NET MVC [RequireHttps]问题 - 但无法找到这个问题的答案:

I've read thru many of the questions on ASP.NET MVC [RequireHttps] - but can't find the answer to this question:

你怎么做[RequireHttps]属性中的URL转换为https如果不是HTTPS与启动?

How do you make the [RequireHttps] attribute switch the url to https if it was not https to start with?

我有这样的code:

public ActionResult DoSomething()
{
    return View("AnotherAction");
}

[RequireHttps]
public ActionResult AnotherAction()
{
    return View();
}

不过,我得到一个错误说:所请求的资源只能通过SSL访问

But I get an error saying: "The requested resource can only be accessed via SSL."

该MVC期货的项目也有类似的属性[RequireSsl(重定向= TRUE)。但是,现在已经过时了......在MVC 2相当于是什么?

The MVC futures project has a similar attribute [RequireSsl(Redirect = true)]. But that is outdated now ... What is the equivalent in MVC 2?

当有人类型的网址 http://example.com/home/dosomething 或网址的http://example.com/home/anotheraction ,我需要他们被自动重定向到URL https://example.com/家/ anotheraction

When someone types in the URL http://example.com/home/dosomething OR the url http://example.com/home/anotheraction, I need them to be automatically redirected to the url https://example.com/home/anotheraction

编辑这是事件的顺序:

该网址 http://example.com/home/dosomething 是从其他网站调用。他们重定向其用户此URL(用的Response.Redirect或类似)。

The URL http://example.com/home/dosomething is called from another website. They redirect their users to this url (with a response.redirect or similar).

DoSomething的(),然后试图返回AnotherAction(),但失败,出现错误消息所请求的资源只能通过SSL进行访问。

DoSomething() then tries to return AnotherAction(), but fails with the error message "The requested resource can only be accessed via SSL."

推荐答案

RequiresHttps 属性不会自动尝试重定向到 https://开头的-url 。我验证网站上的这种行为我有一个使用该属性,也期待在反射器code:

The RequiresHttps attribute does automatically attempt to redirect to https://your-url. I verified this behavior on a site I have that uses that attribute, and also looking at the code in Reflector:

protected virtual void HandleNonHttpsRequest(AuthorizationContext filterContext)
{
    if (!string.Equals(filterContext.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
    {
        throw new InvalidOperationException(MvcResources.RequireHttpsAttribute_MustUseSsl);
    }
    string url = "https://" + filterContext.HttpContext.Request.Url.Host + filterContext.HttpContext.Request.RawUrl;
    filterContext.Result = new RedirectResult(url);
}

你确定你有你的站点设置了接受安全连接? ?//你的URL 直接

这篇关于MVC RequireHttps如果没有HTTPS重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆