Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change webapi controller action parameter in delegatinghandler

I have an action in my controller that derives from ApiController (MVC4 WebApi):

[HttpGet] 
public IEnumerable<SomeDto> GetData(string username)
{
    return dbReader.GetSomeDtosByUser(username);
}

I have a delegatinghandler with SendAsync-method as:

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
    ModifyUserNameInRequestQueryParams(request);
    base.SendAsync(request, cancellationToken);
}

public void ModifyUserNameInRequestQueryParams(Request request)
{
    var nameValues = request.RequestUri.ParseQueryString();
    nameValues.Set("username", "someOtherUsername");
    var uriWithoutQuery = request.RequestUri.AbsoluteUri.Substring(0, request.RequestUri.AbsoluteUri.IndexOf(request.RequestUri.Query));
    request.RequestUri = new Uri(uriWithoutQuery + "?" + nameValues);
}

I can see that the request uri is updated correctly (when I debug GetData) but the parameter username in GetData is always the same as before I changed it.

Is there any other way to change this parameter value if not by changing the request queryparams in the delegatinghandler?

like image 660
Jon Lindeheim Avatar asked Feb 22 '26 13:02

Jon Lindeheim


1 Answers

I tried your scenario and it works just fine...not sure if there is a mistake somewhere else...are you sure you added the message handler? :-)

Also if using message handler is not a strict requirement, then you can do something like the following too:

public class ValuesController : ApiController
{
    [CustomActionFilter]
    public string GetAll(string username)
    {
        return username;
    }
}

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        object obj = null;
        if(actionContext.ActionArguments.TryGetValue("username", out obj))
        {
            string originalUserName = (string)obj;

            actionContext.ActionArguments["username"] = "modified-username";
        }
    }
}
like image 167
Kiran Avatar answered Feb 24 '26 02:02

Kiran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!