Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

Custom ParameterBindingAttribute in ASP.NET Web Api

How can I implement custom ParameterBindingAttribute similar [FromBody]

// POST api/<controller>
public void Post([FromBody]string value)
{
}

For example do something like

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Parameter, Inherited = true, AllowMultiple = false)]
public sealed class EncodeAttribute : ParameterBindingAttribute
{

    public override HttpParameterBinding GetBinding(HttpParameterDescriptor parameter)
    {
        //1.get parameter value
        //2.change value
        //3.bindig value
    }
}

Upvotes: 4

Views: 1926

Answers (1)

Ilya Sulimanov
Ilya Sulimanov

Reputation: 7836

Solved the problem by creating custom BinderType

public string Get([FromUri(BinderType = typeof(UrlToFileSystemMapping))]string path = "")
{              

}

public class UrlToFileSystemMapping : IModelBinder
{
    bool IModelBinder.BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
        if (val != null)
        {
            var s = val.AttemptedValue as string;
            if (s != null)
            {
                bindingContext.Model = s.Replace('|', '\\');    
                return true;
            }
        }
        return false;
    }
}

Upvotes: 3

Related Questions