ASP.NET Core 5 was just released and it includes a number of new features. Earlier I mentioned the built-in support for OpenAPI and Swagger UI via Swashbuckle in the new ASP.NET Core 5 Web API Project Template. Another new feature is improved model binding to support C# 9 record types.

The C# 9 record type is perfect for use as data transfer objects where immutability is valuable. Using them for view models in ASP.NET Core MVC and for transferring data back and forth from an ASP.NET Core Web API seem like good applications for record types.

ASP.NET Core Web API and C# 9 Record Type

I spinned up a really quick ASP.NET Core 5 Web API that uses C# 9 record types to transfer data to and from the client. I created a couple of record types that represented adding a new contact and returning a contact from the Web API.

public record NewContact(
    [Required]string FirstName,
    [Required]string LastName,
    [Required]int? Age
);

public record Contact(
    int Id,
    string FirstName,
    string LastName,
    int Age
);

I then created a simple APIController with a few actions. The most important action is the Post action that accepts a new contact from the client.

[HttpPost]
public async Task<ActionResult<Contact>> Post([FromBody]NewContact newContact)
{
    var contact = _mapper.Map(newContact);

    _repository.Add(contact);
    await _repository.SaveChangesAsync();

    return CreatedAtAction("Get", new { id = contact.Id }, _mapper.Map(contact));
}

Sending a JSON post request to the APIController using Postman with a new contact successfully returns a status code of 201 Created as one would expect.

{
    // Send

    "FirstName": "Jane",
    "LastName": "Doe",
    "Age": 25
}
{
    // Return

    "Id": 1,
    "FirstName": "Jane",
    "LastName": "Doe",
    "Age": 25
}

Not that I doubted the announcement :), but indeed the new C# 9 record type is fully supported by ASP.NET Core 5 during model binding. I don't know for sure, but I suspect the Microsoft ASP.NET Team didn't have to do anything special to support the new record type. It is a class after all, and it's the C# compiler that does some cool code generation under the covers to give it some special features.

Wrap Up

If you haven't already, download the .NET 5 SDK or the latest preview of Visual Studio 2019 to get ASP.NET Core 5 and C# 9. Create a new ASP.NET Core 5 Web API Project and give this a shot yourself. And, if you're unfamiliar with the new record type in C# 9, check out my tutorial: C# 9 Record Type.