Click here to Skip to main content
15,909,939 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
In the last couple of MVC applications that I have made, each Controller action is preceded by this little snippet of code:
C#
[HttpGet] // or [HttpPost]
#if (DEBUG == false)
  [RequireHttps]
#endif
public ActionResult Index()
{
  // do something
}
I do this so that ISS Express can load up the website without any special HTTPS processing but I want the whole site to require HTTPS once past the login screen once it's loaded to the production server.

What I would like to know is if there is an alternative to using #if...#endif conditional compilation to add in attributes only for Release builds.

What I have tried:

I searched but I haven't been able to find any decent alternatives other than writing a whole class to wrap the Controller class. Conditional attributes look promising but I am not seeing how they could be applied to this situation.
Posted
Updated 30-Oct-17 4:36am

1 solution

I believe that those lines are there because the developer won't be bothered to set up a 'Self Signed Certificate' in the local IIS...
It is easy and very advised if you are writing an HTTPS-only site anyway...

[EDIT]
And set HTTPS on site level using (on application start):
C#
GlobalFilters.Filters.Add(new RequireHttpsAttribute());
 
Share this answer
 
v2
Comments
Foothill 30-Oct-17 11:01am    
You can create self-signed certificates for ISSExpress!? You learn something new every day. I assumed something as bare-bones as IISExpress wouldn't have that capability. Do you have a link to the steps?

While you did provide a viable work-around, the original question still remains unanswered and I am still curious if precompiler directives can be replaced in C#.
Kornfeld Eliyahu Peter 30-Oct-17 11:09am    
I think this will help you to configure IISExpress: https://www.hanselman.com/blog/WorkingWithSSLAtDevelopmentTimeIsEasierWithIISExpress.aspx (but I would say - use IIS even for development)...
As for #if #endif - I do not know any other structure to replace it, but in your case you can move it to application start (put Filters.Add in condition) and leave actions clear of that...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900