Skip to main content

Store complex objects in ASP.NET Core Session

The ASP.NET Core Session object has 3 methods to set the session value, which are Set, SetInt32 and SetString. The Set method accepts a byte array as an argument where the SetInt32 and SetString method are the extension methods of the Set method. These methods internally cast the int or string to a byte array. Similar to these, there are 3 methods used to retrieve the value from the session: Get, GetInt32 and GetString. There is no method available to store complex objects in session, and this post shows how to store complex objects in ASP.NET Core Session. Read More

Validate Model State automatically in ASP.NET Core 2.0

A ModelState is a collection of name and value pairs submitted to the server during a POST request. It also contains a collection of error messages for each value. The Modelstate represents validation errors in submitted HTML form values. Model validation is the first statement in each controller action method to check for any error before moving forward. A familiar piece of code.

The IsValid property will be true when the values are attached correctly to the model AND no validation rules are broken in the binding process. However, writing this piece of code in every action method increases efforts, lines of code and repetitiveness. It would be appropriate to make model validation a reusable piece or even better would be to automate this process. This post talks about how to validate model state automatically in ASP.NET Core 2.0.
Read More

Quick Tip – Return HTTP Status Code from ASP.NET Core Methods

It is advisable to return the proper HTTP status code in response to a client request. This helps the client to understand the request’s result and then take corrective measure to handle it. Proper use of the status codes will help to handle a request’s response in an appropriate way. Out of the box, ASP.NET Core has inbuilt methods for the most common status codes. Like,

  • return Ok(); // Http status code 200
  • return Created(); // Http status code 201
  • return NoContent(); // Http status code 204
  • return BadRequest(); // Http status code 400
  • return Unauthorized(); // Http status code 401
  • return Forbid(); // Http status code 403
  • return NotFound(); // Http status code 404

Read More