Skip to content

Instantly share code, notes, and snippets.

@vanillajonathan
Created April 11, 2018 12:49
Show Gist options
  • Save vanillajonathan/356c401de55cd4f7b83372b154cbf42b to your computer and use it in GitHub Desktop.
Save vanillajonathan/356c401de55cd4f7b83372b154cbf42b to your computer and use it in GitHub Desktop.
Serialize content into a ModelStateDictionary.
public static class HttpContentExtensions
{
/// <summary>
/// Serialize the HTTP content to a <see cref="ModelStateDictionary"/> as an asynchronous operation.
/// </summary>
/// <returns>A <see cref="ModelStateDictionary"/> that contains validation errors.</returns>
public static async Task<ModelStateDictionary> ReadAsModelStateAsync(this HttpContent content)
{
var fields = await content.ReadAsAsync<IDictionary<string, string[]>>();
var modelState = new ModelStateDictionary();
foreach (var field in fields)
{
foreach (var errorMessage in field.Value)
{
modelState.AddModelError(field.Key, errorMessage);
}
}
return modelState;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment