ASP.NET Core Tips and Tricks

There are some differences with ASP.NET and ASP.NET Core that warrant a separate section.

Tips and Tricks

  1. Use Uri.EscapeDataString() and Uri.EscapeUriString() to encode data URI strings. To encode "/How now brown cow" using EscapeDataString: %2FHow%20now%20brown%20cow and EscapeUriString: /How%20now%20brown%20cow
  2. Alternatively, use System.Net.WebUtility.UrlEncode("string to encode") or System.Web.HttpUtility.UrlEncode("string to encode") to encode a URI string. These do the same thing.
  3. Sets the cache control headers. Duration sets "max-age" in "Cache-control" header. Location sets where the data must be cached. NoStore, if true, ignores Location and Duration and sets "Cache-control" header to "no-store".
    using Microsoft.AspNetCore.Mvc;
    
    namespace Website.Controllers
    {
    	public class HomeController : Controller
    	{
    		// set Duration to 0 and NoStore to true to prevent caching
    		[ResponseCache(Duration = 86400, Location = ResponseCacheLocation.Client, NoStore = false)]
    		public string Index()
    		{
    			return "";
    		}
    	}
    }
    
  4. Inject HTML code into a view with a simple, single line:
    @{
    	Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8" />
    	<title></title>
    </head>
    <body>
    	@Html.Partial("_PartialViewToInject")
    	<-- OR -->
    	<partial name="_PartialViewToInject" />
    </body>
    </html>
    
  5. The ASP.NET Core MVC designers made it very simple to download a file:
    using Microsoft.AspNetCore.Mvc;
    
    namespace Website.Controllers
    {
    	public class HomeController : Controller
    	{
    		public FileResult DownloadFile()
    		{
    			return File("/test.txt", "text/plain");
    		}
    	}
    }
    
  6. Access the query string parameters from within the View:
    @{
    	Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8" />
    	<title></title>
    </head>
    <body>
    	<p>param=@Context.Request.Query["param"]</p>
    </body>
    </html>
    
  7. Access the Content Directory by saving the IHostingEnvironment argument of the controller constructor.
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    
    namespace Website.Controllers
    {
    	public class HomeController : Controller
    	{
    		private IHostingEnvironment env { get; }
    
    		public HomeController(IHostingEnvironment env) => this.env = env;
    
    		public string Index()
    		{
    			return env.ContentRootPath; // or env.WebRootPath
    		}
    	}
    }
    
  8. Get the remote IP address of the connection.
    using Microsoft.AspNetCore.Mvc;
    
    namespace Website.Controllers
    {
    	public class HomeController : Controller
    	{
    		public string Index()
    		{
    			return HttpContext.Connection.RemoteIpAddress.ToString();
    			// within a VIEW use Context.Connection.RemoteIpAddress
    		}
    	}
    }
    
  9. Set the content-type header from within a view.
    @{
    	Context.Response.ContentType = "application/javascript";
    }
    ... content here ...
    
  10. Run this code to to see all that is available from Context.Request. Some will return objects, like collections, and most properties are able to be set on the Context.Response object.
    @{
    	Layout = null;
    }
    <!DOCTYPE html>
    <html>
    <head>
    	<meta charset="utf-8" />
    	<title></title>
    </head>
    <body>
    <pre>
    Context.Request.Body=@Context.Request.Body
    Context.Request.ContentType=@Context.Request.ContentType
    Context.Request.Cookies=@Context.Request.Cookies
    Context.Request.HasFormContentType=@Context.Request.HasFormContentType
    Context.Request.Headers=@Context.Request.Headers
    Context.Request.Host=@Context.Request.Host
    Context.Request.HttpContext=@Context.Request.HttpContext
    Context.Request.IsHttps=@Context.Request.IsHttps
    Context.Request.Method=@Context.Request.Method
    Context.Request.Path=@Context.Request.Path
    Context.Request.PathBase=@Context.Request.PathBase
    Context.Request.Protocol=@Context.Request.Protocol
    Context.Request.Query=@Context.Request.Query
    Context.Request.Query["param"]=@Context.Request.Query["param"]
    Context.Request.QueryString=@Context.Request.QueryString
    Context.Request.Scheme=@Context.Request.Scheme
    </pre>
    </body>
    </html>
    

    This is the output:

    Context.Request.Body=Microsoft.AspNetCore.Server.IIS.Core.HttpRequestStream
    Context.Request.ContentType=
    Context.Request.Cookies=Microsoft.AspNetCore.Http.Internal.RequestCookieCollection
    Context.Request.HasFormContentType=False
    Context.Request.Headers=Microsoft.AspNetCore.HttpSys.Internal.RequestHeaders
    Context.Request.Host=www.prowaretech.com
    Context.Request.HttpContext=Microsoft.AspNetCore.Http.DefaultHttpContext
    Context.Request.IsHttps=False
    Context.Request.Method=GET
    Context.Request.Path=/
    Context.Request.PathBase=
    Context.Request.Protocol=HTTP/1.1
    Context.Request.Query=Microsoft.AspNetCore.Http.Internal.QueryCollection
    Context.Request.Query["param"]=123
    Context.Request.QueryString=?param=123
    Context.Request.Scheme=http