How do I enable ssl for all controllers in mvc app

2020-06-09 07:52发布

I have a MVC 5 app and I installed the ssl certificate and I'm now connecting with https, but in my code I had to set the '[requirehttps]' attribute on the homecontroller like so:

[RequireHttps]
public class HomeController : Controller
{}

Isn't there a way to set it for the whole application so I don't have to do this for each and every controller I have in the app?

2条回答
甜甜的少女心
2楼-- · 2020-06-09 08:08

Use the RegisterGlobalFilters method in your FiltersConfig.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new RequireHttpsAttribute());
    }
}
查看更多
姐就是有狂的资本
3楼-- · 2020-06-09 08:12

The [RequireHttps] attribute is inherited, so you could create a base controller, apply the attribute to that, and then derive all your controllers from that base.

[RequireHttps]
public abstract class BaseController : Controller
{}

public class HomeController : BaseController
{}

public class FooController : BaseController
{}
查看更多
登录 后发表回答