Skip to content

Instantly share code, notes, and snippets.

@postb99
Last active April 1, 2019 13:56
Show Gist options
  • Save postb99/18ff42d68890e6e994b2cd5b070b0c4f to your computer and use it in GitHub Desktop.
Save postb99/18ff42d68890e6e994b2cd5b070b0c4f to your computer and use it in GitHub Desktop.
Custom model binding to add XmlSerializer deserialization errors to model state (asp .net core mvc)
// Thanks to : https://www.dotnetcurry.com/aspnet-mvc/1261/custom-model-binder-aspnet-mvc
// and https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding?view=aspnetcore-2.2
// model binder
public class SmartXmlModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
try
{
var modelType = bindingContext.ModelType;
var serializer = new XmlSerializer(modelType);
var receivedStream = bindingContext.HttpContext.Request.Body;
var modelValue = serializer.Deserialize(receivedStream);
bindingContext.Result = ModelBindingResult.Success(modelValue);
}
catch (Exception ex)
{
bindingContext.ModelState.AddModelError("ModelError", $"{ex.Message} {ex.InnerException?.Message}");
}
return Task.CompletedTask;
}
}
// model binder provider
public class SmartXmlModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
return new SmartXmlModelBinder();
}
}
// Startup.cs
services.AddMvc(
opts =>
{
// ... other usual options ...
// add custom binder to beginning of collection
opts.ModelBinderProviders.Insert(0, new SmartXmlModelBinderProvider());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment