Exclude documentation when deploying to production - asp.net

I have a Web API project in ASP .NET where I have some web services.
I use the comments of the methods to generate the help pages created by default in Visual Studio.
// GET api/version
/// <summary>
/// Test
/// </summary>
/// <returns></returns>
public string Get()
{
return "Last version : 74";
}
It is usefull for a development environment but we don't want these pages to appear on the production environment.
Is there any way to exclude them from deployment on production?
I tried to delete the files and make sure the web services calls still works, they do, but I am not sure of which files I can delete and I am wondering if there is any safer/automatic way to do it?
Here is the list of files I have at the moment :
ApplicationInsights.config
App_Data
Areas
bin
Content
favicon.ico
fonts
Global.asax
Scripts
Views
Web.config
WsCommon.wpp.targets

Publish the web site to a local folder and deploy those contents, they will only contain the essential files.
Deploy that folder, or if possible, just publish to your target site.

I ended up doing the following :
File App_Start/RouteConfig.cs
Ignore the route to the HelpPages in DEBUG Configuration
public static void RegisterRoutes(RouteCollection routes)
{
[...]
#if DEBUG
routes.IgnoreRoute("Help");
#endif
[...]
}
File Global.asax.cs
protected void Application_Start()
{
[...]
#if DEBUG
AreaRegistration.RegisterAllAreas();
#endif
[...]
}
File Controllers/HomeController.cs
Should return a 404 error instead of an index in production :
public ActionResult Index()
{
ViewBag.Title = "Home Page";
#if DEBUG
return View();
#else
return HttpNotFound();
#endif
}
This way, the help pages url return the help pages in Debug and 404 errors in Release. No need to do any further manipulation with the files from

Related

How to dump entire appsettings.json file in ASP.NET Core Web API

I am trying to create a simple GET API endpoint which will return the JSON of the current environment appsettings.json file, for example for the development environment it will return the contents of appsettings.Development.json file and for production environment it will return the contents of appsettings.Production.json file.
I don't know a nice way to dump the entire config file. What I know though is ways to read single config values through the injected config["Key"] or read a section through
config.GetSection("SectionName").Get<MyCustomSectionClass>()
approach. These options are not feasible as the file is big and the content may change.
This is an ASP.NET Core 6 Core Web API application, created through the default Visual Studio template.
If you want to return entire appsettings.xxx.json file, You can try this simple demo. I not sure if there is a better method, But this method works well in my project.
using Newtonsoft.Json;
private readonly IWebHostEnvironment _env;
public WeatherForecastController(IWebHostEnvironment env)
{
_env = env;
}
[HttpGet]
public IActionResult Get()
{
if (_env.IsDevelopment())
{
var path = Path.Combine(_env.ContentRootPath, "appsettings.Development.json");
string json = System.IO.File.ReadAllText(path);
object jsonObject = JsonConvert.DeserializeObject(json);
return Ok(jsonObject);
}else if (_env.IsProduction())
{
//read from appsettings.Production.json
return Ok();
}
else
{
//..........
return Ok();
}
}

Can't handle routing correctly in mixed VS environment

I am creating a new project in Visual Studio using the SPA template. My goal is to have an Angular/SPA application that will "host"/contain some legacy applications that will eventually be modernized/migrated. So, I have an iframe on a page in my SPA app, and when a menu item is clicked, I want to load one of the legacy ASP.NET apps in that iframe (it has to be in an iframe, as the legacy site used them, and its architecture relies on them).
I am having trouble getting the routing right. The SPA template defines a DefaultRoute class like this (I changed RouteExistingFiles to true):
public class DefaultRoute : Route
{
public DefaultRoute()
: base("{*path}", new DefaultRouteHandler()) {
this.RouteExistingFiles = true;
}
}
and I have edited the RouteConfig.cs file to ignore "aspx" page requests, like this:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes) {
routes.Ignore("*.aspx");
routes.Add("Default", new DefaultRoute());
}
}
The default route handler that is defined, looks like this:
public class DefaultRouteHandler : IRouteHandler
{
public IHttpHandler GetHttpHandler(RequestContext requestContext) {
// Use cases:
// ~/ -> ~/views/index.cshtml
// ~/about -> ~/views/about.cshtml or ~/views/about/index.cshtml
// ~/views/about -> ~/views/about.cshtml
// ~/xxx -> ~/views/404.cshtml
var filePath = requestContext.HttpContext.Request.AppRelativeCurrentExecutionFilePath;
if (filePath == "~/") {
filePath = "~/views/index.cshtml";
}
else {
if (!filePath.StartsWith("~/views/", StringComparison.OrdinalIgnoreCase)) {
filePath = filePath.Insert(2, "views/");
}
if (!filePath.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase)) {
filePath = filePath += ".cshtml";
}
}
var handler = WebPageHttpHandler.CreateFromVirtualPath(filePath); // returns NULL if .cshtml file wasn't found
if (handler == null) {
requestContext.RouteData.DataTokens.Add("templateUrl", "/views/404");
handler = WebPageHttpHandler.CreateFromVirtualPath("~/views/404.cshtml");
}
else {
requestContext.RouteData.DataTokens.Add("templateUrl", filePath.Substring(1, filePath.Length - 8));
}
return handler;
}
}
The directory structure is like this:
MySPA
SPA <- contains the SPA application (.net 4.5)
Legacy <- contains the legacy applications (.net 3.0)
In IIS, I have the legacy folder set as a virtual directory (subdirectory) within the SPA application.
How do I set up routing so that, when a menu item is clicked, and the request is sent (containing a url that has query string information) for an .aspx page, the request can be routed to the legacy application?
I have solved this issue. The issue was caused by several problems. But, the problem that most pertains to my information above was this...I needed to find the correct way to ignore the requests for the legacy aspx pages from within the routing code of the new site. So, in the RouteConfig.cs file, I placed this ignore statement as the first line of the RegisterRoute function:
routes.Ignore("{*allaspx}", new { allaspx = #".*\.aspx(/.*)?"});
That corrected the main issue, there were other minor issues that confused the situation but, I have identified what they are and I am working on those. So, ignoring the legacy urls in the routing functionality was the correct solution.

Configure Spring MVC application to make changes to html files/templates without recompiling

I have a very simple Spring 4.0 Boot project. I would like to start the application and be able to make changes to the html files located in /templates/ on the fly, without having to stop and restart the application. Changes to static assets, like java scripts or css files, is no problem.
Below are the details of my program:
There are no XML configuration files. This class is used for configuration.
#Configuration
public class MVCConfiguration extends WebMvcConfigurerAdapter{
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("assets/**")
.addResourceLocations("classpath:/templates/assets/");
registry.addResourceHandler("/css/**")
.addResourceLocations("/css/");
registry.addResourceHandler("/img/**")
.addResourceLocations("/img/");
registry.addResourceHandler("/js/**")
.addResourceLocations("/js/");
}
}
This is my controller.
#Controller
public class ControlFreak {
#RequestMapping(value = "/", method = RequestMethod.GET)
public String index(){
return "index";
}
}
I have index.html located in templates/
I run the application using this class.
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
What you are trying to achieve is easily done using an IDE and will save a heck of a lot of time during development.
First of all you need to configure Spring Boot to not cache Thymeleaf templates by setting:
spring.thymeleaf.cache=false
Then you just need to start the application using the IDE in debug mode (just Debug the class with the main method) and whenever you make change to a Thymeleaf Template you just need to instruct the IDE to reload the project.
In IntelliJ IDEA, that is done from the Reload Changed Classes option in the Run menu.
I think you can configure Eclipse to automatically update the project on each change, but it's been a while since I have used it.
Path to project
project.base-dir=file:///C:/temp/auth/
Templates reloading during development
spring.thymeleaf.prefix=${project.base-dir}/src/main/resources/templates/
spring.thymeleaf.cache=false
Static resources reloading during development
spring.resources.static-locations=${project.base-dir}/src/main/resources/static/
spring.resources.cache-period=0

Publish my MVC3 site on localhost

I am trying to publish my mvc web site on the localhost through visual studio but the problem is when i browse to the the localhost in the browser it gives me a directory listing page. here is the screen shot of publish dialogue. Can somebody please guide me through the process i have been searching for the whole day but couldn't get it to work
here id the global.ascx
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute("Facebook",
"XdReceiver",
new { controller = "Account", action = "XdReceiver" });
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
Do you have a requirement to use WebDeploy for your publish? If not, you could create a directory and point IIS to that directory and change your publish method to File System.
IMO, WebDeploy is overkill for localhost deployments if you're using it simply for testing. WebDeploy becomes very useful for network deployments since it compares the contents of the directories and maintains which files have been updated and which ones have not.
just create a empty site using IIS. and then publish the site in visual studio using the File System publish method.
Try checking the "Mark as IIS application on destination" option.
Also, try publishing to Default Web Site/Rental and accessing it as http://localhost/Rental.
If you installed IIS after installing .NET, did you run aspnet_regiis -i? And could you please post your Global.asax file with MVC routes?

MVC3 - All routing works locally but not remotely

I have a new MVC3 project with one Controller called PublicController.cs which contains 4 identical methods for testing out how routing works. The only difference between them is their name, and that they each point to a different view ...
public class PublicController : Controller
{
//
// GET: /Public/
public ActionResult Index()
{
return View();
}
//
// GET: /Public/App
public ActionResult App()
{
return View();
}
//
// GET: /Public/Press
public ActionResult Press()
{
return View();
}
//
// GET: /Public/Contact
public ActionResult Contact()
{
return View();
}
}
I can get to all of them when running in the development server by visiting these URLs...
http://localhost:53367/Public/
or its equivalent
http://localhost:53367/Public/Index
and then
http://localhost:53367/Public/App
http://localhost:53367/Public/Press
http://localhost:53367/Public/Contact
However, once it's deployed to my remote ASP.NET 4.0 server, the only two that work are:
http://localhost:53367/Public
http://localhost:53367/Public/Index
... all others give me a 404 Resource cannot be found error.
My web-server is shared hosting with netcetera, using a sub-domain for this deployment (previously had problems with MVC in virtual directories, but have full blown MVC2 apps running in sub-domains no problem). I've deployed by using the "Publish to file system" option, then copying over the files aswell as just copying the entire source project over. Both give identical results.
Any ideas why?
Thanks,
Steven
Did you make sure MVC 3 Framework is installed to the web server, and that your site's app pool is set to 4.x ASP.net?

Resources