【问题标题】:Modify GetQueryNameValuePairs() for UrlHelper.Link in ASP.NET WebApi修改 ASP.NET WebApi 中 UrlHelper.Link 的 GetQueryNameValuePairs()
【发布时间】:2014-09-16 12:57:11
【问题描述】:

使用 ASP.NET WebApi,当我发送 GET api/question?page=0&name=qwerty&other=params 并且 API 应该在分页信封内给出结果。

为此,我想将结果并将给定的page 查询字符串更改为其他值。

我尝试了下面的代码,但我对此有一种不好的感觉。

protected HttpResponseMessage CreateResponse(HttpStatusCode httpStatusCode, IEnumerable<Question> entityToEmbed)

    // get QueryString and modify page property
    var dic = new HttpRouteValueDictionary(Request.GetQueryNameValuePairs());
    if (dic.ContainsKey("page"))
        dic["page"] = (page + 1).ToString();
    else
        dic.Add("page", (page + 1).ToString());

    var urlHelper = new UrlHelper(Request);
    var nextLink= page > 0 ? urlHelper.Link("DefaultApi", dic) : null;

    // put it in the envelope
    var pageEnvelope = new PageEnvelope<Question>
        {
            NextPageLink = nextLink,
            Results = entityToEmbed
        };

        HttpResponseMessage response = Request.CreateResponse<PageEnvelope<Question>>(httpStatusCode, pageEnvelope, this.Configuration.Formatters.JsonFormatter);
        return response;
    }

NextPageLink 给出了很多复杂的结果。:
http://localhost/api/Question?Length=1&amp;LongLength=1&amp;Rank=1&amp;SyncRoot=System.Collections.Generic.KeyValuePair%602%5BSystem.String%2CSystem.String%5D%5B%5D&amp;IsReadOnly=False&amp;IsFixedSize=True&amp;IsSynchronized=False&amp;page=1

我的问题是,

  1. 我使用Dictionary 方法处理的页面看起来很脏而且错误。有没有更好的方法来解决我的问题?
  2. 我不知道为什么urlHelper.Link(routeName, dic) 会给出如此冗长的 ToString 结果。如何摆脱不可用的字典相关属性?

【问题讨论】:

    标签: c# asp.net-web-api query-string


    【解决方案1】:

    您的代码中的关键问题可能是转换为 HttpRouteValueDictionary。而是新建它并在循环中添加所有键值对。

    该方法可以简化很多,您可能还应该考虑使用 HttpActionResult(以便您可以更轻松地测试您的操作。

    你也应该避免使用httproutevaluedictionary,而是写你的 UrlHelper 像

    urlHelper.Link("DefaultApi", new { page = pageNo }) // assuming you just want the page no, or go with the copying approach otherwise.
    

    只需预先计算您的页面编号(并避免使用 ToString);

    将其全部写入 IHttpActionResult 中,该 IHttpActionResult 公开带有页号的 int 属性,这样您就可以轻松地测试操作结果,而无需考虑如何计算分页。

    比如:

    public class QuestionsResult : IHttpActionResult
    {
        public QuestionResult(IEnumerable<Question> questions>, int? nextPage)
        {
           /// set the properties here
        }
    
        public IEnumerable<Question> Questions { get; private set; }
    
        public int? NextPage { get; private set; }
    
        /// ... execution goes here
    
    }
    

    要获取页面编号,请执行以下操作:

    来源 - http://www.asp.net/web-api/overview/releases/whats-new-in-aspnet-web-api-21

    string page = request.Uri.ParseQueryString()["page"]; 
    

    您可以在下面使用此扩展方法(来自 Rick Strahl)

    public static string GetQueryString(this HttpRequestMessage request, string key)
    {      
        // IEnumerable<KeyValuePair<string,string>> - right!
        var queryStrings = request.GetQueryNameValuePairs();
        if (queryStrings == null)
            return null;
    
        var match = queryStrings.FirstOrDefault(kv => string.Compare(kv.Key, key, true) == 0);
        if (string.IsNullOrEmpty(match.Value))
            return null;
    
        return match.Value;
    }
    

    【讨论】:

    • 谢谢。我现在完全使用IHttpActionResult :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多