ASP.NET Web API中的参数绑定 [英] Parameter Binding in ASP.NET Web API

查看:158
本文介绍了ASP.NET Web API中的参数绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Web API中有一个用于身份验证(HMAC)的DelegatingHandler.

I have a DelegatingHandler in my web API for authentification (HMAC).

我想在请求中添加一个GET参数,以将用户的ID返回给我的控制器.

I would like to add a GET parameter to the request to return the user's id to my controller.

在处理程序中,我尝试像这样添加它:

In my handler, I tried adding it like so:

public class SecurityHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        string apikey = request.Headers.GetValues(AuthConfig.ApiKeyHeader).First();
        UserDTO user = UserRepo.GetUser(apikey);
        if (user == null)
        {
            return SendResponseText("Invalid API key");
        }

        // Validate signature ...

        // Add user Id to the URI
        request.RequestUri = new Uri(request.RequestUri.OriginalString + "&UserId=" + user.Id);
        return base.SendAsync(request, cancellationToken);
    }
}

在我的控制器中,我可以从请求uri中获取新添加的参数,但是参数绑定无效

In my controller, I'm able to get the newly added parameter from the request uri, however the parameter binding is not working

public class MyModel
{
    public int UserId { get; set; }
    ...
}

public string Get([FromUri] MyModel model)
{
    // model.UserId has not been set (= 0)
    // Request.RequestUri contains "&UserId=5"
}

更新

我猜想绑定是通过HttpContext中的Params完成的.我尝试过类似的操作,但是Params集合是只读的.

I'm guessing the binding is being done from the Params in the HttpContext. I tried something like this, but Params collection is readonly.

var newContext = request.Properties["MS_HttpContext"] as HttpContextWrapper;
newContext.Request.Params.Add("UserId", "8");
request.Properties.Remove("MS_HttpContext");
request.Properties.Add("MS_HttpContext", newContext);

推荐答案

我已经在我的身边尝试过,并且可以正常工作.

I have tried at my side and it working.

这是我的示例网址.

http://localhost:50382/api/values?UserId=10

这是控制器动作.

public class ValueController : ApiController
{
    public IEnumerable<string> Get([FromUri]Model my)
            {
                return new string[] { "value1", "value2" , my.UserId.ToString() };
            }
}

根据您在此处的评论,我创建了委托处理程序.

As per your comment here I created delegate handler.

  public class MyMessageHandler : DelegatingHandler
  {
    protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var myTempObj = new { id = 20 };
      /* You have to check this and remove this key. If key present that FromUri use cached properties*/
        if (request.Properties.ContainsKey("MS_QueryNameValuePairs"))
        {
            request.Properties.Remove("MS_QueryNameValuePairs");                
        }

        // Now prepare or update uri over here. It will surely work now.
            if (!string.IsNullOrEmpty(request.RequestUri.Query) && request.RequestUri.Query.Contains('?'))
            {
                request.RequestUri = new Uri(request.RequestUri + "&UserID=" + myTempObj.id);
            }
            else
            {
                request.RequestUri = new Uri(request.RequestUri + "?UserID=" + myTempObj.id);
            }    

        return base.SendAsync(request, cancellationToken);
    }
}

这是预期的工作.

如果您的原始请求包含用户ID,则它将被复制,并且将无法使用.返回0.

If your original request contain userid then it get duplicated and it will not work. It return 0.

我也怀疑您使用的是request.RequestUri.OriginalString.只需尝试使用request.RequestUri.可能是OriginalString具有编码值.

I also have doubt that you are using request.RequestUri.OriginalString. Just try to use request.RequestUri. It might possible that OriginalString has encoded value.

这篇关于ASP.NET Web API中的参数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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