How to Deserialize JSON to C# cherry-picking a small portion of JSON data

JSON deserialization in C# refers to the process of forming up .NET objects from a JSON string. Most of the time, this means creating strongly-typed POCOs. However, there are certain situations when we may prefer flexibility over type-inference. For example, cherry-picking a small portion of JSON data, dealing with external JSON data whose structure is largely unknown or changes very often, etc. Dynamic deserialization comes into play for such cases. This does not necessarily mean the use of language’s inbuilt dynamic keyword. There are other ways as well.We are going to see how we can do this using the native System.Text.Json library and the popular Newtonsoft.Json library.

Source: How to Deserialize JSON Into Dynamic Object in C# – Code Maze

Try the new System.Text.Json source generator – .NET Blog

In .NET 6.0, we are shipping a new C# source generator to help improve the performance of applications that use System.Text.Json. In this post, I’ll go over why we built it, how it works, and what benefits you can experience in your application.

Source: Try the new System.Text.Json source generator – .NET Blog

Task Async handling cancellation – Cancellation in Managed Threads | Microsoft Docs

How to handle cancellation of x number of running background tasks.

Source: Cancellation in Managed Threads | Microsoft Docs
Code examples: https://docs.microsoft.com/en-us/dotnet/standard/threading/cancellation-in-managed-threads#code-example

Retry and fault handling in C# .NET

Sometimes you need to implement some sort of retry logic if an error occurs in a c# program.

Existing libraries for retry and fault handling:
Polly
http://www.thepollyproject.org/

CircuitBreaker.Net
https://github.com/alexandrnikitin/CircuitBreaker.Net

Read more about the related Circuit Breaker pattern:

CircuitBreaker
http://martinfowler.com/bliki/CircuitBreaker.html

Circuit Breaker Pattern
https://msdn.microsoft.com/en-us/library/dn589784.aspx

Error handling and policies in general:

https://en.wikipedia.org/wiki/Exception_handling#Restarts_separate_mechanism_from_policy

https://docs.microsoft.com/en-us/dotnet/standard/exceptions/

https://stackify.com/csharp-exception-handling-best-practices/

c# – Ignore XML namespace when modelbinding in asp net core web api

So, in order to be able to modelbind XML to a class without taking namespaces into consideration I created new InputFormatter. And I use XmlTextReader in order to ignore namespaces. Microsoft recommends to use XmlReader rather than XmlTextReader. But since XmlTextReader is there still (in .Net 6.0 Preview 3) I’ll use it for now.

Simply create an inputformatter that inherits from XmlSerializerInputFormatter like so:

public class XmlNoNameSpaceInputFormatter : XmlSerializerInputFormatter
{
    private const string ContentType = "application/xml";
    public XmlNoNameSpaceInputFormatter(MvcOptions options) : base(options)
    {
        SupportedMediaTypes.Add(ContentType);
    }

    public override bool CanRead(InputFormatterContext context)
    {
        var contentType = context.HttpContext.Request.ContentType;
        return contentType.StartsWith(ContentType);
    }

    public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context)
    {
        var type = GetSerializableType(context.ModelType);
        var request = context.HttpContext.Request;

        using (var reader = new StreamReader(request.Body))
        {
            var content = await reader.ReadToEndAsync();
            Stream s = new MemoryStream(Encoding.UTF8.GetBytes(content));

            XmlTextReader rdr = new XmlTextReader(s);
            rdr.Namespaces = false;
            var serializer = new XmlSerializer(type);
            var result = serializer.Deserialize(rdr);
            return await InputFormatterResult.SuccessAsync(result);
        }
    }
}

Then add it to the inputformatters like so to startup.cs:

        services.AddControllers(o => 
        {
            o.InputFormatters.Add(new XmlNoNameSpaceInputFormatter(o));
        })
        .AddXmlSerializerFormatters();

Now we can modelbind Person or any other class no matter if there is namespaces or not in the incoming XML. Thanks to @yiyi-you

Source: c# – Ignore XML namespace when modelbinding in asp net core web api – Stack Overflow

Making ASP.NET Core 3 web API return REST compliant Http return codes

To make an ASP.NET Web Api (core 3+) return valid Http status codes such as 200 OK, 400 Bad request and 404 Not found, use the IActionResult as return type.

Return code 422 can be used instead of 400, read more here: HTTP Status Codes For Invalid Data: 400 vs. 422

Code example C# web API controller “data” endpoint method:

/// <summary>
/// Get data from API
/// </summary>
/// <remarks>
/// GET: api/v1/data?id={id}
/// </remarks>
/// <returns><see cref="IActionResult"/> <see cref="Data"/>Data model</returns>
/// <response code="200">Serialized <see cref="Data"/></response>
/// <response code="400">Invalid id</response>
/// <response code="404">Found no match for id</response>
[ProducesResponseType(typeof(Data), 200)]
[ProducesResponseType(typeof(object), 400)]
[ProducesResponseType(typeof(object), 404)]
[HttpGet("data")]
public IActionResult GetData(string id)
{
    var data = business.GetData(id);
    if (data == null)
    {
        return NotFound(null); //404 not found
    }
    if (data.IsValid)
    {
        return Ok(data); //200 OK, found
    }
    else
    {
        return BadRequest(data.ValidationErrorMessage); //400 bad reqeust validationerror
    }
}

IActionResult type

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type. Some common return types in this category are BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200). Alternatively, convenience methods in the ControllerBase class can be used to return ActionResult types from an action. For example, return BadRequest(); is a shorthand form of return new BadRequestResult();.

Because there are multiple return types and paths in this type of action, liberal use of the [ProducesResponseType] attribute is necessary. This attribute produces more descriptive response details for web API help pages generated by tools like Swagger[ProducesResponseType] indicates the known types and HTTP status codes to be returned by the action.

More info:
Controller action return types in ASP.NET Core web API | Microsoft Docs
HTTP Status Codes For Invalid Data: 400 vs. 422

ASP.NET Core 2.2 preview – Updated routing handling

We’re making a big investment in routing starting in 2.2 to make it interoperate more seamlessly with middleware. For 2.2 this will start with us making a few changes to the routing model, and adding some minor features. In 3.0 the plan is to introduce a model where routing and middleware operate together naturally. This post will focus on the 2.2 improvements, we’ll discuss 3.0 a bit further in the future.

Source: ASP.NET Core 2.2.0-preview1: Endpoint Routing | ASP.NET Blog

Architect modern web applications with ASP.NET Core and Azure | Microsoft Docs

.NET Core and ASP.NET Core offer several advantages over traditional .NET development. You should use .NET Core for your server applications if some or all of the following are important to your application’s success:

  • Cross-platform support

  • Use of microservices
  • Use of Docker containers
  • High performance and scalability requirements
  • Side-by-side versioning of .NET versions by application on the same server

PDF:
https://raw.githubusercontent.com/dotnet-architecture/eShopOnWeb/master/docs/Architecting%20Modern%20Web%20Applications%20with%20ASP.NET%20Core%20and%20Azure.pdf

Online: Architect modern web applications with ASP.NET Core and Azure | Microsoft Docs

Choose between .NET Core and .NET Framework for server apps | Microsoft Docs

There are two supported implementations for building server-side applications with .NET: .NET Framework and .NET Core. Both share many of the same components and you can share code across the two. However, there are fundamental differences between the two and your choice depends on what you want to accomplish. This article provides guidance on when to use each.

Source: Choose between .NET Core and .NET Framework for server apps | Microsoft Docs