Web API form-urlencoded binding to different property names - c#

I am expecting a POST request with content type set to:
Content-Type: application/x-www-form-urlencoded
Request body looks like this:
first_name=john&last_name=banana
My action on controller has this signature:
[HttpPost]
public HttpResponseMessage Save(Actor actor)
{
....
}
Where Actor class is given as:
public class Actor
{
public string FirstName {get;set;}
public string LastName {get;set;}
}
Is there a way to force Web API to bind:
first_name => FirstName
last_name => LastName
I know how to do it with requests with content type set to application/json, but not with urlencoded.

I'm 98% certain (I looked the source code) that WebAPI doesn't support it.
If you really need to support different property names, you can either:
Add additional properties to the Actor class which serves as alias.
Create your own model binder.
Here is a simple model binder:
public sealed class ActorDtoModelBinder : IModelBinder
{
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
var actor = new Actor();
var firstNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "First_Name"));
if(firstNameValueResult != null) {
actor.FirstName = firstNameValueResult.AttemptedValue;
}
var lastNameValueResult = bindingContext.ValueProvider.GetValue(CreateFullPropertyName(bindingContext, "Last_Name"));
if(lastNameValueResult != null) {
actor.LastName = lastNameValueResult.AttemptedValue;
}
bindingContext.Model = actor;
bindingContext.ValidationNode.ValidateAllProperties = true;
return true;
}
private string CreateFullPropertyName(ModelBindingContext bindingContext, string propertyName)
{
if(string.IsNullOrEmpty(bindingContext.ModelName))
{
return propertyName;
}
return bindingContext.ModelName + "." + propertyName;
}
}
If you are up for the challenge, you can try to create a generic model binder.

It's an old post but maybe this could helps other people.
Here is a solution with an AliasAttribute and the associated ModelBinder
It could be used like this :
[ModelBinder(typeof(AliasBinder))]
public class MyModel
{
[Alias("state")]
public string Status { get; set; }
}
Don't hesitate to comment my code :)
Every Idea / comment is welcome.

Related

Check coherence between route and body data during .NET Core validation

I'm trying to find the "best" way to check the coherence between data in the request URL and data in the body of the request.
For example, let's say we have this PUT endpoint:
https://host:port/foo/bar/{carId}
where I can pass a Car object as body:
class Car {
string CarId { get; set; }
string Brand { get; set; }
int MaxSpeed { get; set; }
...
}
Now, in my controller I have something like this:
[HttpPut("foo/bar/{carId}")]
public async Task updateCar([FromRoute] string carId, [FromBody] Car car) {
...
}
And I want to be sure that carId in the route matches the CarId property in the body.
What is the "best" way to achieve this? Of course I could simply check with an if in the body controller, but since this is a validation task (or at least I think so), I'd like to have this logic in my validation layer.
Personal ideas so far
Ok, the question is over, here I'll just put some ideas I've tried or I want to try.
I have a custom action filter to check the validation, and I'm trying to play with it in order to see if I can do something there, or add another custom action filter only where I want to check the coherence, but this doesn't look promising.
At the moment I've seen that in an action filter I have access to the controller method parameters through context.ActionArguments property, but I don't know how to check if these arguments were "bound arguments" (namely had some [FromXXX] attribute). If I could do this maybe I could check if there are arguments with the same name (or with a property with the same name), and then compare their values. But this seems very cumbersome and inconsistent.
I've read about custom binders, but I'm still scratching the surface (I hope to learn something more in the next few hours): can they be a possible solution?
You should do it like this:
[AttributeUsage(AttributeTargets.Property)]
public class VerifyWithRouteParams : Attribute
{
public string ParamName
{
get
{
return paramName;
}
}
private readonly string paramName;
public VerifyWithRouteParams(string paramName)
{
this.paramName = paramName;
}
}
Consider you have a car model that is being recieved through body:
public class Car
{
[VerifyWithRouteParams("carId")]
public string CarId { set; get; }
public string AnotherParam {set; get;}
}
You should have a default filter:
public class RouteBodyVerificationActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
// do something before the action executes
if (context.ActionArguments != null && context.ActionArguments.Count > 0)
{
foreach (var arg in context.ActionArguments)
{
if (arg.Value == null) continue;
bool isThereAnyObjectInArgumentsWithVerificationAttribute = arg.Value
.GetType()
.GetProperties()
.Any(
x => x.GetCustomAttributes(typeof(VerifyWithRouteParams), false).Any()
);
if (isThereAnyObjectInArgumentsWithVerificationAttribute)
{
foreach (var prop in arg.Value.GetType().GetProperties())
{
var verificationAttr = prop.GetCustomAttributes(typeof(VerifyWithRouteParams), false).FirstOrDefault() as VerifyWithRouteParams;
if (null == verificationAttr) continue;
string routeArgumentName = verificationAttr.ParamName;
context.ActionArguments.TryGetValue(routeArgumentName, out var routeArgumentValue);
if (null == routeArgumentValue)
{
context.ModelState.AddModelError("invalid argument value", routeArgumentName);
}
if (routeArgumentValue?.Equals(prop.GetValue(arg.Value)) != true)
{
context.ModelState.AddModelError("invalid argument value", routeArgumentName);
}
}
}
}
}
}
}
Then you should add a default filter in startup:
services.AddControllers(cfg =>
{
cfg.Filters.Add<RouteBodyVerificationActionFilter>();
});
Then you can check it by model validation errors in controller:
if (!ModelState.IsValid)
{
return Content("invalid model");
}

Handle dot (.) character in parameter name in post request

I'm building a restful server to handle post requests. However, there is a dot (.) in one of the parameter names which I don't know how to handle since C# does not allow dot (.) in their variable names. The parameter name is "data.json" without the quotation.
I read some posts about C# converting dots (.) into underscores (_), so I tried to name the variable "data_json", which doesn't work, the string is empty.
Object Class:
public class Lead {
public string data_json { get; set; }
public string page_id { get; set; }
public string page_url { get; set; }
}
Post Handler:
public HttpResponseMessage Post(Lead value) {
try {
Log.CreatePostLog(page_id + value.data_json);
} catch (Exception e) {
return Request.CreateResponse(HttpStatusCode.BadRequest, e.Message);
}
return Request.CreateResponse(HttpStatusCode.OK, "Done!");
}
Post Request Body (Cannot be changed):
page_url=http://ramdomurl/
&page_id=123456
&data.json={"time_submitted":["04:34 PM UTC"],"full_name":["John Doe"]}
When the request is made, the log shows page_id but nothing after.
It should show page_id and the Json string after it.
One possible solution is to create a custom model binder, which handles fields whose names contain the "." character, and apply this binder to the model class.
The code of the binder:
// this binder assigns form fields with dots to properties with underscores:
// e.g. data.json -> data_json
public class Dot2UnderscoreModelBinder : IModelBinder
{
// for regular fields, we will use the default binder
private readonly DefaultModelBinder _default = new DefaultModelBinder();
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
// handle the regular fields
var model = _default.BindModel(controllerContext, bindingContext);
// handle the special fields
if (model != null)
{
var modelType = model.GetType();
var form = controllerContext.HttpContext.Request.Form;
foreach (var key in form.AllKeys)
{
if (key.Contains(".")) // special field
{
// model property must be named by the convention "." -> "_"
var propertyName = key.Replace(".", "_");
var propertyInfo = modelType.GetProperty(propertyName);
propertyInfo?.SetValue(model, form[key]);
}
}
}
return model;
}
}
Note that this is a simplistic implementation, it only supports string properties, and its performance is not optimal. But it is a working starting point.
Now you need to apply the above binder to the model class:
[ModelBinder(typeof(Dot2UnderscoreModelBinder))]
public class Lead
{
//... properties
}
It worth noting that the controller must derive from Controller in System.Web.Mvc namespace, and not ApiController in System.Web.Http, because that latter doesn't trigger model binders:
using System.Web.Mvc;
....
public class MyController : Controller
{
[HttpPost]
public ActionResult Post(Lead value)
{
//... do some stuff
return base.Content("Done!");
}
}
ASP.NET Core
Just as a side note, in ASP.NET Core the same can be achieved in a very simple way, by applying FromForm attribute:
public class Lead
{
[FromForm(Name = "data.json")] // apply this attribute
public string data_json { get; set; }
//... other properties
}
Use NewtonsoftJson PropertyName attribute:
public class Lead
{
[JsonProperty(PropertyName = "data.json")]
public string data_json { get; set; }
public string page_id { get; set; }
public string page_url { get; set; }
}
Add nuget package:
https://www.nuget.org/packages/Newtonsoft.Json/

Postman Form Data to ASP.NET Core 2.2 Controller not binding to Command with private setters

Tools
Visual Studio 2017
ASP.NET Core 2.2
Postman v7.2.0
What I'm trying to do
Send FormData from Postman to an ASP.NET Core controller and have the data from the request bind to to a command class that has properties with private setters.
I've sent JSON data using the same setup (private setters) with no problem. The FromBody attribute deserialises the JSON string to the model without errors.
The Problem
Properties that are primitive types do not bind if the model has a private setter. However, complex types do regardless of the access modifier.
Controller
[HttpPost]
[ProducesResponseType((int)HttpStatusCode.OK)]
[ProducesResponseType((int)HttpStatusCode.BadRequest)]
public async Task<IActionResult> CreateItemAsync([FromForm]CreateItemCommand command)
{
bool result = false;
commandResult = await _mediator.Send(command);
if (!commandResult)
{
return BadRequest();
}
return Ok();
}
Command
Note: The Title property has been left with a public setter deliberately to illustrate the behviour
[DataContract]
public class CreateItemCommand
:IRequest<bool>
{
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; private set; }
[DataMember]
public int Count { get; private set; }
[DataMember]
public HashSet<string> Tags { get; private set; }
[DataMember]
public string ItemDate { get; private set; }
[DataMember]
public List<IFormFile> Documents { get; private set; }
public CreateItemCommand()
{
Skills = new HashSet<string>();
Systems = new HashSet<string>();
}
public CreateItemCommand(string title, string description,
int count, HashSet<string> tags, string itemDate,
List<IFormFile> documents)
: this()
{
Title = title;
Description = description;
Count = count
Tags = tags;
ItemDate = itemDate;
Documents = documents;
}
}
In Postman I now setup the request as follows:
I've had to obfuscate some of the information, but you can see that the primitive types with private setters are not set.
Questions
Why does the property access modifier only affect properties with primitive types?
Why does this happens when the parameter attribute is set to FromForm but not when it's set to FromBody
Why does the property access modifier only affect properties with primitive types?
For Asp.Net Core ModelBinder, it will check whether the property is private access setter by ComplexTypeModelBinder code below:
protected virtual object CreateModel(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// If model creator throws an exception, we want to propagate it back up the call stack, since the
// application developer should know that this was an invalid type to try to bind to.
if (_modelCreator == null)
{
// The following check causes the ComplexTypeModelBinder to NOT participate in binding structs as
// reflection does not provide information about the implicit parameterless constructor for a struct.
// This binder would eventually fail to construct an instance of the struct as the Linq's NewExpression
// compile fails to construct it.
var modelTypeInfo = bindingContext.ModelType.GetTypeInfo();
if (modelTypeInfo.IsAbstract || modelTypeInfo.GetConstructor(Type.EmptyTypes) == null)
{
var metadata = bindingContext.ModelMetadata;
switch (metadata.MetadataKind)
{
case ModelMetadataKind.Parameter:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForParameter(
modelTypeInfo.FullName,
metadata.ParameterName));
case ModelMetadataKind.Property:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForProperty(
modelTypeInfo.FullName,
metadata.PropertyName,
bindingContext.ModelMetadata.ContainerType.FullName));
case ModelMetadataKind.Type:
throw new InvalidOperationException(
Resources.FormatComplexTypeModelBinder_NoParameterlessConstructor_ForType(
modelTypeInfo.FullName));
}
}
_modelCreator = Expression
.Lambda<Func<object>>(Expression.New(bindingContext.ModelType))
.Compile();
}
return _modelCreator();
}
Why does this happens when the parameter attribute is set to FromForm but not when it's set to FromBody
For FromBody, it is used JsonInputFormatter to bind the model from the body request, it's used JsonConvert.DeserializeObject to deserilize the object and Newtonsoft.Json support deserize the object which contains private setter from json string.

Customize attribute names with Web API default model binder?

I have a request model class that I'm trying to use the default Web API 2 model binding (.NET 4.6.1). Some of the query string parameters match the model properties, but some do not.
public async Task<IHttpActionResult> Get([FromUri]MyRequest request) {...}
Sample query string:
/api/endpoint?country=GB
Sample model property:
public class MyRequest
{
[JsonProperty("country")] // Did not work
[DataMember(Name = "country")] // Also did not work
public string CountryCode { get; set; }
// ... other properties
}
Is there a way to use attributes on my model (like you might use [JsonProperty("country")]) to avoid implementing a custom model binding? Or is best approach just to use create a specific model for the QueryString to bind, and then use AutoMapper to customize for the differences?
Late answer but I bumped into this issue recently also. You could simply use the BindProperty attribute:
public class MyRequest
{
[BindProperty(Name = "country")]
public string CountryCode { get; set; }
}
Tested on .NET Core 2.1 and 2.2
Based on further research, the default model binding behavior in Web API does not support JsonProperty or DataMember attributes, and most likely solutions seem to be either (1) custom model binder or (2) maintaining 2 sets of models and a mapping between them.
JSON to Model property binding using JsonProperty
Changing the parameter name Web Api model binding
I opted for the custom model binder (implementation below) so I could re-use this and not have to duplicate all my models (and maintain mappings between every model).
Usage
The implementation below allows me to let any model optionally use JsonProperty for model binding, but if not provided, will default to just the property name. It supports mappings from standard .NET types (string, int, double, etc). Not quite production ready, but it meets my use cases so far.
[ModelBinder(typeof(AttributeModelBinder))]
public class PersonModel
{
[JsonProperty("pid")]
public int PersonId { get; set; }
public string Name { get; set; }
}
This allows the following query string to be mapped in a request:
/api/endpoint?pid=1&name=test
Implementation
First, the solution defines a mapped property to track the source property of the model and the target name to use when setting the value from the value provider.
public class MappedProperty
{
public MappedProperty(PropertyInfo source)
{
this.Info = source;
this.Source = source.Name;
this.Target = source.GetCustomAttribute<JsonPropertyAttribute>()?.PropertyName ?? source.Name;
}
public PropertyInfo Info { get; }
public string Source { get; }
public string Target { get; }
}
Then, a custom model binder is defined to handle the mapping. It caches the reflected model properties to avoid repeating the reflection on subsequent calls. It may not be quite production ready, but initial testing has been promising.
public class AttributeModelBinder : IModelBinder
{
public static object _lock = new object();
private static Dictionary<Type, IEnumerable<MappedProperty>> _mappings = new Dictionary<Type, IEnumerable<MappedProperty>>();
public IEnumerable<MappedProperty> GetMapping(Type type)
{
if (_mappings.TryGetValue(type, out var result)) return result; // Found
lock (_lock)
{
if (_mappings.TryGetValue(type, out result)) return result; // Check again after lock
return (_mappings[type] = type.GetProperties().Select(p => new MappedProperty(p)));
}
}
public object Convert(Type target, string value)
{
try
{
var converter = TypeDescriptor.GetConverter(target);
if (converter != null)
return converter.ConvertFromString(value);
else
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
catch (NotSupportedException)
{
return target.IsValueType ? Activator.CreateInstance(target) : null;
}
}
public void SetValue(object model, MappedProperty p, IValueProvider valueProvider)
{
var value = valueProvider.GetValue(p.Target)?.AttemptedValue;
if (value == null) return;
p.Info.SetValue(model, this.Convert(p.Info.PropertyType, value));
}
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
try
{
var model = Activator.CreateInstance(bindingContext.ModelType);
var mappings = this.GetMapping(bindingContext.ModelType);
foreach (var p in mappings)
this.SetValue(model, p, bindingContext.ValueProvider);
bindingContext.Model = model;
return true;
}
catch (Exception ex)
{
return false;
}
}
}

How to: Parameter binding from multiple sources

Currently I'm trying to create a web api based on asp.net core 2.0 and I'd like to create a nested route. In case of a put request it sends a part of the information in the route and another part in the body.
Requirements
The desired url to call would be
https://localhost/api/v1/master/42/details
If we'd like to create a new detail below our master 42 I would expect to send the data of the details in the body while the id of the master comes out of the route.
curl -X POST --header 'Content-Type: application/json' \
--header 'Accept: application/json' \
-d '{ \
"name": "My detail name", \
"description": "Just some kind of information" \
}' 'https://localhost/api/v1/master/42/details'
The outcoming response of the request would be
{
"name": "My detail name",
"description": "Just some kind of information",
"masterId": 42,
"id": 47
}
and a location url within the response header like
{
"location": "https://localhost/api/v1/master/42/details/47
}
Work done so far
To get this to work I created this controller:
[Produces("application/json")]
[Route("api/v1/master/{masterId:int}/details")]
public class MasterController : Controller
{
[HttpPost]
[Produces(typeof(DetailsResponse))]
public async Task<IActionResult> Post([FromBody, FromRoute]DetailCreateRequest request)
{
if(!ModelState.IsValid)
return BadRequest(ModelState);
var response = await Do.Process(request);
return CreatedAtAction(nameof(Get), new { id = response.Id }, response);
}
}
Which uses these classes:
public class DetailCreateRequest
{
public int MasterId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class DetailResponse
{
public int Id { get; set; }
public int MasterId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The problem
So far most of the stuff works as expected. The only thing that really doesn't work is merging the MasterId from the route into the DetailCreateRequest that comes from the body.
First try: Use two attributes on the parameter
I tried to combine these two things by this action call:
public async Task<IActionResult> Post([FromBody, FromRoute]DetailCreateRequest request)
But the incoming object only had a MasterId of zero. If I change the order of the two attributes, then only the id from the route will be taken and all values within the body are ignored (so seems to be first attribute wins).
Second try: Use two different parameters in action
Another approach that I tried was this action call:
public async Task<IActionResult> Post([FromRoute]int masterId, [FromBody]DetailCreateRequest request)
In the first spot this looks okay, cause now I have both values within the controller action. But my big problem with this approach is the model validation. As you can see in the above code I check ModelState.IsValid which was filled through some checks from FluentValidation, but these checks can't be really done, cause the object wasn't build up correctly due to the missing master id.
(Not-working) Idea: Create own attribute with merge parameters
Tried to implement something like this:
public async Task<IActionResult> Post([FromMultiple(Merge.FromBody, Merge.FromRoute)]DetailCreateRequest request)
If we already would have something like this, that would be great. The order of the arguments within the attribute would give out the order in which the merge (and possible overwrites) would happen.
I already started with implementing this attribute and creating the skeleton for the needed IValueProvider and IValueProviderFactory. But it seems to be a quite lot of work. Especially finding all the nifty details to make this work seamlessly with the whole pipeline of asp.net core and other libraries I'm using (like swagger through swashbuckle).
So my question would be, if there already exists some mechanism within asp.net core to achieve such a merge or if anybody is aware about an already existing solution or about a good example on how to implement such a beast.
Solution so far: Custom ModelBinder
After getting the answer from Merchezatter I look into how to create a custom model binder and came up with this implementation:
public class MergeBodyAndValueProviderBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
throw new ArgumentNullException(nameof(bindingContext));
var body = bindingContext.HttpContext.Request.Body;
var type = bindingContext.ModelMetadata.ModelType;
var instance = TryCreateInstanceFromBody(body, type, out bool instanceChanged);
var bindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
var setters = type.GetProperties(bindingFlags).Where(property => property.CanWrite);
foreach (var setter in setters)
{
var result = bindingContext.ValueProvider.GetValue(setter.Name);
if (result != ValueProviderResult.None)
{
try
{
var value = Convert.ChangeType(result.FirstValue, setter.PropertyType);
setter.SetMethod.Invoke(instance, new[] { value });
instanceChanged = true;
}
catch
{ }
}
}
if (instanceChanged)
bindingContext.Result = ModelBindingResult.Success(instance);
return Task.CompletedTask;
}
private static object TryCreateInstanceFromBody(Stream body, Type type, out bool instanceChanged)
{
try
{
using (var reader = new StreamReader(body, Encoding.UTF8, false, 1024, true))
{
var data = reader.ReadToEnd();
var instance = JsonConvert.DeserializeObject(data, type);
instanceChanged = true;
return instance;
}
}
catch
{
instanceChanged = false;
return Activator.CreateInstance(type);
}
}
}
It tries to deserialize the body into the desired object type and afterwards tries to apply further values from the available value providers. To get this model binder to work I had to decorate the destination class with the ModelBinderAttribute and made the MasterId internal, so that swagger doesn't announce it and JsonConvert doesn't deserialize it:
[ModelBinder(BinderType = typeof(MergeBodyAndValueProviderBinder))]
public class DetailCreateRequest
{
internal int MasterId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
Within my controller the action method parameters are still containing the [FromBody] flag, cause it is used by swagger to announce on how the method can be called, but it never will be called, cause my model binder has a higher priority.
public async Task<IActionResult> Post([FromBody]DetailCreateRequest request)
So it is not perfect, but works good so far.
That is looks like a right choice:
[HttpPost]
[Produces(typeof(DetailsResponse))]
public async Task<IActionResult> Post([FromRoute]int masterId, [FromBody]DetailCreateRequest request) {
//...
}
But if you have some problems with domain model validation, create custom Dto object without master Id.
Otherwise you can use custom model binder, and then work with arguments from action and binding contexts.
I'm not sure if this works in Asp.Net-Core 2.0, but we use the following in 3.1 to have a single request object which gets its properties from multiple locations:
// Annotate the action parameter with all relevant attributes
public async Task<IActionResult> Post([FromBody][FromRoute][FromQuery]DetailCreateRequest request) { ... }
// Annotate each property separately, so the binder(s) don't overwrite
public class DetailCreateRequest
{
[FromRoute]
public int MasterId { get; set; }
[FromBody]
public string Name { get; set; }
[FromQuery]
public string Description { get; set; }
}
It works with .Net 6:
[HttpPost]
[Route("{id}")]
public async Task<ActionResult<CustomerResponse>> Post([FromRoute, FromBody] CustomerPostRequest request)
{
return Ok();
}
public class CustomerPostRequest
{
[FromRoute(Name = "id")]
public int Id { get; set; }
[FromBody]
public string Name { get; set; }
}
Set the your required "source" attributes on the single request object parameter, and inside this object add each property the relevant "source" attribute.
Make sure the FromBody is the last one (it didn't work when I switched them).

Categories