在delegatinghandler中更改webapi控制器操作参数 [英] Change webapi controller action parameter in delegatinghandler

查看:165
本文介绍了在delegatinghandler中更改webapi控制器操作参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个动作是从ApiController(MVC4 WebApi)派生的:

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

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

我有一个使用SendAsync方法的委托处理程序:

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

我可以看到请求uri已正确更新(当我调试GetData时),但是GetData中的参数用户名始终与更改前相同.

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.

如果不通过更改委托处理程序中的请求queryparams,是否还有其他方法可以更改此参数值?

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

这篇关于在delegatinghandler中更改webapi控制器操作参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆