2

I have the following enum for Web API 2:

[TypeConverter(typeof(StringEnumConverter))]
public enum SortDirection
{
    [EnumMember(Value = "asc")] Ascending,
    [EnumMember(Value = "desc")] Descending
}

I'm using the TypeConverterAttribute with StringEnumConverter from Newtonsoft.Json. If I serialize this enum to JSON it ends up looking like I want it:

// "property": "asc"
// "property": "desc"

I'd like to be able to bind this to a model coming from the URI in Web API so that I can pass in ?direction=desc

public class ExampleController : ApiController
{
    public IHttpActionResult GetAll([FromUri]SortDirection sortDir)
    {
        // the above property is not binding to value asc / dir from the query string
        // it only binds to 0/1 or Ascending/Descending
    }
}

Currently, I can pass in ?direction=0|1 or ?direction=Ascending|Descending and Web API will bind it.

I would like to be able to do this without referring to SortDirection explicitly...any enum that I have which uses EnumMemberAttribute I would like to apply this logic to.

How can I accomplish this?

Dismissile
  • 32,564
  • 38
  • 174
  • 263
  • I'm removing my answer. What I see now, you have to write your own Filter attribute of type ActionFilterAttribute and to apply it to controller. Override it's method "OnActionExecuting" and manually parse values (you just need to find parameter of enum type and put appropriate value). See also HttpActionContext.ActionDescriptor.GetParameters() and HttpActionContext.ActionArguments – Evgeny Gorbovoy Apr 11 '18 at 15:58
  • You need to implement a custom parameter binding : [here](https://stackoverflow.com/questions/48457738/raw-post-data-deserialization-using-c-net-bind-to-complex-model-like-in-mode/48462293#48462293) a simple exemple to transform for your need – Troopers Apr 11 '18 at 16:17

0 Answers0