【问题标题】:How to get parameter from URL in actionContext ASP.NET Web API 2如何从 actionContext ASP.NET Web API 2 中的 URL 获取参数
【发布时间】:2021-11-06 04:58:09
【问题描述】:

如果我有这样的路线:

api/account/{id}/devices

如何在操作过滤器中从actionContext 获取id 值?

当路由是api/account/{id}我用过

actionContext.Request.RequestUri.Segments.Last()

如果我知道参数名称,但不知道它在 url 中的位置,是否有可靠的方法从 url 字符串中获取任何参数?

ActionContext.ActionArguments 为空,顺便说一句)。

【问题讨论】:

    标签: c# asp.net-web-api2


    【解决方案1】:

    @orsvon 将我推向了一个正确的方向:
    What is Routedata.Values[""]?
    在 web api 中没有 ViewBag,但想法是正确的。
    对于在这里绊倒的人:
    如果你有一些过滤器或属性并且你需要获取一些参数,你可以这样做:

    public class ContractConnectionFilter : System.Web.Http.AuthorizeAttribute
    {
        private string ParameterName { get; set; }
    
        public ContractConnectionFilter(string parameterName)
        {
            ParameterName = parameterName;
        }
        
        private object GetParameter(HttpActionContext actionContext) 
        {
            try
            {
                return actionContext.RequestContext.RouteData.Values
                    //So you could use different case for parameter in method and when searching
                    .Where(kvp => kvp.Key.Equals(ParameterName, StringComparison.OrdinalIgnoreCase))
                    .SingleOrDefault()
                    //Don't forget the value, Values is a dictionary
                    .Value;
            }
            catch
            {
                return null;
            }
        }
    
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            object parameter = GetParameter(actionContext);
            ... do smth...
        }
    }
    

    并像这样使用它:

    [HttpGet, Route("account/{id}/devices/{name}")]
    [ContractConnectionFilter(parameterName: "ID")] //stringComparison.IgnereCase will help with that
    //Or you can omit parameterName at all, since it's a required parameter
    //[ContractConnectionFilter("ID")]
    public HttpResponseMessage GetDevices(Guid id, string name) {
        ... your action...
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-02
      • 2015-12-21
      • 2014-09-29
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      相关资源
      最近更新 更多