简体   繁体   中英

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?

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";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM