Skip to content

Instantly share code, notes, and snippets.

@xiaomi7732
Created August 10, 2023 01:35
Show Gist options
  • Save xiaomi7732/2b531bad9a6f88ee49483a1975a47166 to your computer and use it in GitHub Desktop.
Save xiaomi7732/2b531bad9a6f88ee49483a1975a47166 to your computer and use it in GitHub Desktop.
Handling Special Characters in RouteValues for CreatedAtAction

Handling Special Characters in RouteValues for CreatedAtAction

When working with ASP.NET and the CreatedAtAction method, the process of providing route values is often straightforward. Consider the following example:

[HttpPost]
public async Task<IActionResult> Post(ApiVersion apiVersion)
{
    ...
    var routeValues = new 
    {
        version = "1.0",
        otherValue = "abc"
    };
    return CreatedAtAction(nameof(Get), routeValues, new { jobId });
}

In this context, the resulting URL in the headers will appear as: http://...?version=1.0&otherValue=abc

However, things can become a bit tricky when dealing with characters that are not valid for C# property names, yet are allowed in query parameters. Imagine wanting to create a URL like:

http://...?api-version=1.0&otherValue=abc

Here, the parameter name "api-version" is acceptable for a query parameter, but cannot be used as a property name in C# due to the presence of a hyphen.

To overcome this challenge, a solution is to utilize a dictionary instead of anonymous object:

Dictionary<string, string> routeValues = new()
{
    ["api-version"] = "1.0",
    ["otherValue"] = "abc",
};
return CreatedAtAction(nameof(Get), routeValues, new { jobId });

By employing a dictionary, you can flexibly specify keys with special characters, such as hyphens, that are not valid in C# property names. The CreatedAtAction method will then adeptly construct the URL, incorporating the provided dictionary of route values into the query parameters.

In essence, this approach offers a practical way to generate URLs with query parameters that include characters unsuitable for C# property naming conventions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment