PROWAREtech

articles » current » asp-net-core » tips-and-tricks

ASP.NET Core: Tips and Tricks

Useful tips and tricks for the budding ASP.NET Core developer; examples in C#.

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

Tips and Tricks

  1. Use System.IO.Path.Combine() and System.IO.Path.DirectorySeparatorChar to correctly form paths based on the operating system file and directory path rules (Windows paths versus Linux/MacOS paths).
  2. Use Uri.EscapeDataString() to encode data URI strings. To encode "/How now brown cow" using EscapeDataString: Uri.EscapeDataString("/How now brown cow") =
  3. 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.
  4. 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 "";
    		}
    	}
    }
    
  5. 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>
    
  6. 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");
    		}
    	}
    }
    
  7. 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>
    
  8. 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
    		}
    	}
    }
    
  9. 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
    		}
    	}
    }
    
  10. Set the content-type header from within a view.
    @{
    	Context.Response.ContentType = "application/javascript";
    }
    ... javascript code here ...
    
  11. 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
    

PROWAREtech

Hello there! How can I help you today?
Ask any question

PROWAREtech

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
ACCEPT REJECT