DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • Lightning Data Service for Lightning Web Components
  • An Introduction to Object Mutation in JavaScript
  • Understanding the Differences Between Repository and Data Access Object (DAO)

Trending

  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Scalable, Resilient Data Orchestration: The Power of Intelligent Systems
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  • How AI Agents Are Transforming Enterprise Automation Architecture
  1. DZone
  2. Data Engineering
  3. Data
  4. Serializing Objects to URL Encoded Form Data

Serializing Objects to URL Encoded Form Data

I was writing integration tests and I wanted to re-use some model classes instead of dictionaries. Here's how I did it.

By 
Gunnar Peipman user avatar
Gunnar Peipman
·
May. 14, 19 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
16.5K Views

Join the DZone community and get the full member experience.

Join For Free

While messing with dictionaries to create form data for FormUrlEncodedContent to see I could send data to a server using an HTTP client, I started thinking about easier and cleaner ways to do it. I was writing integration tests and I wanted to re-use some model classes instead of dictionaries. Here's how to do it. Sample integration test is incluced.

Those who are currently writing integration tests for some ASP.NET Core web applications may also find the following writings interesting:

  • Using custom appsettings.json with ASP.NET Core integration tests
  • Using custom startup class with ASP.NET Core integration tests
  • Using ASP.NET Core Identity user accounts in integration tests
  • File uploads in ASP.NET Core integration tests

Problem

I write integration tests for ASP.NET Core web application. There are tests that use HTTP POST to send some data to a server. I can create a POST body as shown here.

var formDictionary = new Dictionary<string, string>();
formDictionary.Add("Id", "1");
formDictionary.Add("Title", "Item title");
 
var formContent = new FormUrlEncodedContent(formDictionary);
 
var response = await client.PostAsync(url, formContent);

I don't like this code and I would use it only if other options turn out to be less optimal. Instead, I want something like this:

var folder = new MediaFolder { Id = 1, Title = "Folder title" };
 
var formBody = GetFormBodyOfObject(folder);
 
// Act
var response = await client.PostAsync(url, fromBody);

Or why not something more elegant like the code here:

var folder = new MediaFolder { Id = 1, Title = "Folder title" };
 
// Act
var response = await client.PostAsync(url, folder.ToFormBody());

This way I can use model classes from web applications because these classes are used on forms anyway to move data between a browser and a server. If otherwise breaking changes are introduced then the compiler will tell me about it.

Serializing Objects to Dictionary<string,string>

Thanks to Arnaud Auroux from Geek Learning, we have a ready-made solution. The ToKeyValue() method by Arnaud turns objects to JSON and then uses the Newtonsoft.JSON library to convert the object toa  dictionary like the FormUrlEncodedContent class wants.

The ToKeyValue() method is the main work horse for my solution. I turned it into an extension method and made it a serializer to avoid cyclic references.

public static IDictionary<string, string> ToKeyValue(this object metaToken)
{
    if (metaToken == null)
    {
        return null;
    }
 
    // Added by me: avoid cyclic references
    var serializer = new JsonSerializer { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
    var token = metaToken as JToken;
    if (token == null)
    {
        // Modified by me: use serializer defined above
        return ToKeyValue(JObject.FromObject(metaToken, serializer));
    }
 
    if (token.HasValues)
    {
        var contentData = new Dictionary<string, string>();
        foreach (var child in token.Children().ToList())
        {
            var childContent = child.ToKeyValue();
            if (childContent != null)
            {
                contentData = contentData.Concat(childContent)
                                         .ToDictionary(k => k.Key, v => v.Value);
            }
        }
 
        return contentData;
    }
 
    var jValue = token as JValue;
    if (jValue?.Value == null)
    {
        return null;
    }
 
    var value = jValue?.Type == JTokenType.Date ?
                    jValue?.ToString("o", CultureInfo.InvariantCulture) :
                    jValue?.ToString(CultureInfo.InvariantCulture);
 
    return new Dictionary<string, string> { { token.Path, value } };
}

Now we can serialize our objects to Dictionary<string,string> and it also works with object hierarchies.

Serializing Objects to Form Data

But we are not there yet. The ToKeyValue() extension method is useful if we want to modify a dictionary before it goes to FormUrlEncodedContent. For cases when we don't need any modifications to the dictionary, I wrote the ToFormData() extension method.

Using these extension methods, I can write integration tests as shown here.

[Fact]
public async Task CreateFolder_CreatesFolderWithValidData()
{
    // Arrange
    var factory = GetFactory(hasUser: true);
    var client = factory.CreateClient();
    var url = "Home/CreateFolder";
 
    var folder = new MediaFolder { Id = 1, Title = "Folder title" };
 
    // Act
    var response = await client.PostAsync(url, folder.ToFormData());
 
    // Assert
    response.EnsureSuccessStatusCode(); // Status Code 200-299
    Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
}

Wrapping Up

We started with an annoying problem and ended up with a pretty nice solution. Instead of manually filling dictionaries used for HTTP POST requests in integration tests, we found nice a JSON-based solution by Arnaud Auroux and we built the ToKeyValue() and ToFormData() extension methods to simplify object serialization to .NET Core HttpClient form data. These extension methods are general enough to have them in some common library for our projects.

Object (computer science) Data (computing) Form (document) integration test ASP.NET Core

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • GDPR Compliance With .NET: Securing Data the Right Way
  • Lightning Data Service for Lightning Web Components
  • An Introduction to Object Mutation in JavaScript
  • Understanding the Differences Between Repository and Data Access Object (DAO)

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!