4

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.

3 Answers 3

3

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.

1

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; }
}
1
  • doesn't appear to work in .net 5.0. The [FromRoute] parameter is null since [FromBody] appears to take precedence and then stops checking for additional values. It does work (e.g. from a GET) though if you do not include [FromBody]... e.g. [FromHeader][FromRoute][FromQuery] works on a GET... and you only need to annotate the model properties with the correct attributes. As long as the method has one of any appropriate annotation (e.g. pick [FromHeader] at random), it will work.
    – GrahamB
    Oct 29, 2021 at 11:16
1

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).

1
  • I meant "FromBody". Fixed that. Thanks!
    – YanivHer
    Nov 6, 2022 at 14:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.