Integrating ASP.NET Core 2.0 MVC with Angular 5- Part II — Zerone Consulting

Integrating ASP.NET Core 2.0 MVC with Angular 5

In the previous post, we saw the step-by-step procedure for creating a new project with ASP.NET Core 2.0 MVC with Angular 5. To make the optimal use of the MVC features, you need to perform some configurations on the following features:

  • Session
  • Exception handling and action logging
  • Action filter
  • Reading appsettings.json

You need to enable session in the Startup.cs for using the session features. To enable session and session state, the following code should be replaced:

Replace the above code with the following:

public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddSessionStateTempDataProvider(); services.AddSession(); }

In ASP.NET Core 2.0 session, the value is stored as a byte array. You can store any value inside the session. Use the below code for setting and getting byte arrays to the session.

HttpContext.Session.Set("key", bytearray); HttpContext.Session.TryGetValue("key", out bytearray);

You can convert values to a byte array using the following code:

byte[] ObjectToByteArray(object obj) { if (obj == null) { return null; } BinaryFormatter bf = new BinaryFormatter(); using (MemoryStream ms = new MemoryStream()) { bf.Serialize(ms, obj); return ms.ToArray(); } }

You can retrieve values from byte array using the following code:

private Object ByteArrayToObject(byte[] arrBytes) { MemoryStream memStream = new MemoryStream(); BinaryFormatter binForm = new BinaryFormatter(); memStream.Write(arrBytes, 0, arrBytes.Length); memStream.Seek(0, SeekOrigin.Begin); Object obj = (Object)binForm.Deserialize(memStream); return obj; }

Exception handling and action logging

Using the middleware pipeline, you can intercept all actions in ASP.NET Core. For that, you need to create a Middleware class and configure it in the application globally.

First, you need to create the class ActionMiddleware.cs

public class ActionMiddleware { private readonly RequestDelegate _next; public ActionMiddleware(RequestDelegate next) { next = next; } public async Task Invoke(HttpContext context) { try { //Code for logging all action requests. context.Request will get the request await _next(context); } catch (Exception ex) { string path = context.Request.Path.Value; //Code for logging errors. context.Response.ContentType = "text/plain"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; if (ex is ApplicationException) { await context.Response.WriteAsync(ex.Message); } } } }

The above class can be used for logging requests and handling exceptions. You need to configure the above class in the Configure section in Startup.cs. Add the below line of code in the Configure section in Startup.cs


First, you need to create two classes inheriting Attribute and IActionFilter.

You can register the action filter in the ConfigureServices section in Startup.cs.


Replace the above line in the ConfigureServices section in Startup.cs with the below code:

services.AddMvc(options => { options.Filters.Add(new ValidateSession()); }).AddSessionStateTempDataProvider();

In the action filter, you can check for session expire/ authentication. If the verification fails, the page is redirected to Account/RedirectSessionOut in the case of web requests, and Account/SessionOutAPI in the case of API calls.

You need to return the HTTP 401 error from Account/SessionOutAPI in case of web API calls. Inside the client app, during the error check for HTTP 401 error, you need to figure out if the error is thrown because of a session out or any unauthenticated request that has occurred.

The second class SkipSessionAttribute can be used as an attribute to action, where the session checking needs to be skipped.

SkipSession] public IActionResult Index() { return View(); }

In ASP.NET, there is AppSettings section in web.config file for storing key value pairs. In ASP.NET Core 2.0 there is no web.config file. Instead, there is the appsettings.json file where you can store values.

The advantage of appsettings.json is that you can store settings as multiple sections. For instance, if you need to store some system settings and SMTP settings, you can add two sections: Settings and SmtpConfig to appsettings.json.

Each block is called sections. Now you need to create two classes that contain properties the same as these sections.

Inside the ConfigureServices (IServiceCollection services), you need to configure these configuration sections using dependency injection:

services.Configure<Domain.Settings>(Configuration.GetSection("Settings")); services.Configure<Domain.SmtpConfig>(Configuration.GetSection("Smtp"));

In the above two sections, you can define settings that are common across the system settings file. You need to make this setting available throughout the actions. For this, define it in the ActionMiddleWare class that you have created for logging and exception handling.

Declare the settings class in ActionMiddleWare.cs.

private readonly Settings settings;

In the constructor, assign setting to the declared variable:

public ActionMiddleware(RequestDelegate next, IOptions<Domain.Settings> options) { _next = next; this.settings = options.Value; }

In the Invoke function, add a net item to HttpContext for settings.

In any action, you can get the settings by the below code:

Settings settings = (Settings)(HttpContext.Items["settings"]);

Also, there is another way of accessing appsettings.json. You have configured the SmtpConfig section in ConfigureServices using dependency injection. You can create a constructor for the controller to receive these settings.

private readonly IOptions<Settings> _settings; public HomeController(IOptions<Settings> settings) { _settings = settings; }

Using these two methods you can access AppSettings.json.

Hope these posts help you in integrating ASP.NET Core 2.0 MVC with newly released Angular 5. Try out these steps and let us know your thoughts in the comments section.

Originally published at

Your sure-shot journey towards rapid digital transformation