Custom Middleware in ASP.NET

Option #1: Implementing IMiddleware Add the middleware to DI, and then use it. In the middleware class, use DI for the constructor, and implement the single InvokeAsync method. Option #2: By Convention Use the middleware, but you don’t need to register it in DI. In the middleware class constructor, accept and store the RequestDelegate, then […]

TypeScript settings in csproj

These are the settings I put in the csproj file for TypeScript – it sets values to convert to ES5, takes all TypeScript files and compiles to individual JavaScript files in the /Scripts/js directory. From there, I’ll bundle them into a single site.js file inside of wwwroot/js using BunderMinifier.

Claims Authorization Example

Startup.cs appsettings.json _Layout.cshtml AccessDenied.cshtml Login.cshtml Login.cshtml.cs Admin.cshtml Admin.cshtml.cs Others Repeat for AdminOrCityAdmin.cshtml, PhoenixAdmin.cshtml, UserAccount.cshtml, Zero.cshtml, with the appropriate Authorize attributes representing the policies. Notes Adding the key location and app name to the Startup file gives you the ability to put the keys in a file share and share them among multiple servers in a […]

Type-safe JSON result in ASP.NET MVC

public abstract class BaseController : Controller { protected internal JsonResult<T> Json<T>(T data) { return Json(data, null /* contentType */, null /* contentEncoding */, JsonRequestBehavior.DenyGet); } protected internal JsonResult<T> Json<T>(T data, string contentType) { return Json(data, contentType, null /* contentEncoding */, JsonRequestBehavior.DenyGet); } protected internal virtual JsonResult<T> Json<T>(T data, string contentType, Encoding contentEncoding) { return Json(data, […]

Is Development in Razor View

I find myself needing to know if I’m in development from inside a Razor view. In the C# code, you can generally use the #DEBUG preprocessor directive, but it’s not quite so easy in Razor. I’ve used an extension method on HtmlHelper to kind of cheat, but the “correct” way seems to be to inject […]

MVC Disable Converting Empty String to Null

Some joker decided that empty strings passed into an MVC controller should be converted to null by default. One way to avoid this is to decorate the string properties of the model class: using System.ComponentModel.DataAnnotations; public class SomeModel { [DisplayFormat(ConvertEmptyStringToNull = false)] public string SomeProperty { get; set; }} [HttpPost]public JsonResult DoSomething(SomeModel myModel) { bool […]