3

Is it possible to map parameters from request to properties with different names? I need it because I'd like to use words splitted by underscore as url parameters but in C# code I'd like to use normal convention. Example :

?property_name=1 to property PropertyName

In the request I use [FromUri] parameter like

public IHttpActionResult DoMethod([FromUri(Name = "")] SomeInput input)

Initially I thought that model binding is performed by Json serializer but probably it isn't. I tried DataMember attribute as well but these approaches do not work.

public class SomeInput
{
    [JsonProperty("property_name")]
    [DataMember(Name = "property_name")]
    public int PropertyName { get; set; }
}

I read about the custom binders but I hope some more simple way must exist. Any idea how to do this correctly and simple in ASP.NET Web API 2 with using Owin and Katana?

y0j0
  • 3,369
  • 5
  • 31
  • 52
  • Did you make some changes in your web api configuration? like: formatters, converters etc – MaKCbIMKo May 02 '16 at 15:38
  • Does this answer your question? [Changing the parameter name Web Api model binding](https://stackoverflow.com/q/26600275/5815327) This answer specifically worked for me: https://stackoverflow.com/a/29090053/5815327 – Deantwo Aug 28 '20 at 07:00

2 Answers2

4

You can do a remapping for an individual parameter using the Name property on [FromUri]:

public IHttpActionResult DoMethod([FromUri(Name = "property_name")] int propertyName)

To remap inside a custom object you will need to create a model binder.

Dan Harms
  • 4,725
  • 2
  • 18
  • 28
  • 1
    It is no solution. I have multiple properties inside SomeInput. I use only simplified code in this example. – y0j0 May 02 '16 at 16:43
  • You can do this for as many properties as you'd like. Obviously, it's tedious with a lot of fields. – Dan Harms May 02 '16 at 16:53
  • Yes yo're right but I have more things in wrapping object SomeInput like validations, comments to generate documentation etc. – y0j0 May 03 '16 at 07:24
  • You can always build that object with these fields. – Dan Harms May 03 '16 at 13:32
0

In your model you could do something like this.

using Microsoft.AspNetCore.Mvc;

public class SomeInput
{
  [FromQuery(Name = "property_name")]
  public string PropertyName {get; set;}
    
}

Then in your controller get method access it from the mapped name

[HttpGet]
public IHttpActionResult DoMethod([FromQuery]SomeInput someInput)
{
 someInput.PropertyName 
 ...
}
Zameel
  • 11
  • 2