Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Parameter Names With Special Characters in ASP.NET Web API MVC 4

I have a requirement to create a Get method which takes the following parameter names in the URL:

ms-scale ms-contrast ms-lang

As you can see, all the names have a dash in them which is not possible in C#. How can I map my method to these parameter names?

public HttpResponseMessage Get(int scale, string contrast string lang)
like image 949
Muhammad Rehan Saeed Avatar asked Sep 06 '12 10:09

Muhammad Rehan Saeed


2 Answers

Use FromUriAttribute

public HttpResponseMessage Get([FromUri(Name = "ms-scale")]int scale, [FromUri(Name = "ms-contrast")]string contrast, [FromUri(Name = "ms-lang")]string lang)
like image 84
phdesign Avatar answered Sep 28 '22 04:09

phdesign


I was asked this before somewhere else and found this answer:

Using a dash (-) in ASP.MVC parameters

Updated

In order to get this working with Web API we need to modify it a bit.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class BindParameterAttribute : ActionFilterAttribute
{
    public string ViewParameterName { get; set; }
    public string ActionParameterName { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var viewParameter = actionContext.Request.RequestUri.ParseQueryString()[ViewParameterName];
        if (!string.IsNullOrWhiteSpace(viewParameter))
            actionContext.ActionArguments[ActionParameterName] = viewParameter;

        base.OnActionExecuting(actionContext);
    }
}

And how to use it:

[BindParameter(ActionParameterName = "customData", ViewParameterName = "custom-data")]
public string Get(string customData) {}

Please note, that this only works if your data comes from the uri, not body. How to make it work with POST data, I'm not really sure of at the moment.

like image 32
Kordonme Avatar answered Sep 28 '22 05:09

Kordonme