PROWAREtech
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
- Use
System.IO.Path.Combine()
andSystem.IO.Path.DirectorySeparatorChar
to correctly form paths based on the operating system file and directory path rules (Windows paths versus Linux/MacOS paths). - Use
Uri.EscapeDataString()
to encode data URI strings. To encode "/How now brown cow" usingEscapeDataString
:Uri.EscapeDataString("/How now brown cow")
= - Alternatively, use
System.Net.WebUtility.UrlEncode("string to encode")
orSystem.Web.HttpUtility.UrlEncode("string to encode")
to encode a URI string. These do the same thing. -
Sets the cache control headers.
Duration
sets "max-age" in "Cache-control" header.Location
sets where the data must be cached.NoStore
, if true, ignoresLocation
andDuration
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 ""; } } }
-
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>
-
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"); } } }
-
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>
-
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 } } }
-
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 } } }
-
Set the content-type header from within a view.
@{ Context.Response.ContentType = "application/javascript"; } ... javascript code here ...
-
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 theContext.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
Comment