【问题标题】:URL string generation in .NET.NET 中的 URL 字符串生成
【发布时间】:2012-11-10 15:14:23
【问题描述】:

我想知道 .NET 是否有任何用于简化 URL 生成的类,类似于 Path.Combine 但用于 URL。

我正在寻找的功能示例:

string url = ClassName.Combine("http://www.google.com", "index")
            .AddQueryParam("search", "hello world").AddQueryParam("pagenum", 3);
// Result: http://www.google.com/index?search=hello%20world&pagenum=3

【问题讨论】:

标签: c# .net


【解决方案1】:

我相信您正在寻找UriBuilder 课程。

为统一资源标识符 (URI) 提供自定义构造函数并修改 Uri 类的 URI。

【讨论】:

    【解决方案2】:

    这是一个链接到两个第三方库的类似问题:

    C# Url Builder Class

    据我所知,.NET 中没有任何“开箱即用”的东西允许一个流畅的接口来构造UrlQueryString

    【讨论】:

      【解决方案3】:
      // In webform code behind: 
      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Web;
      using System.Web.UI;
      using System.Web.UI.WebControls;
      using System.Collections.Specialized;
      
      namespace testURL
      {
          public partial class _Default : System.Web.UI.Page
          {
              protected void Page_Load(object sender, EventArgs e)
              {
      
              }
      
              protected void Button1_Click(object sender, EventArgs e)
              {
                  NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty);
      
                  queryString["firstKey"] = "a";
                  queryString["SecondKey"] = "b";
      
                  string url=GenerateURL(queryString); // call function to get the url
              }
      
              private string GenerateURL(NameValueCollection nvc)
              {
                  return "index.aspx?" + string.Join("&", Array.ConvertAll(nvc.AllKeys, key => string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key]))));
              }
      
          }
      }
      
      
          // To get information to generate URL in MVC please check the following tutorial:
          http://net.tutsplus.com/tutorials/generating-traditional-urls-with-asp-net-mvc3/
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-03
        • 2022-11-10
        • 2019-10-04
        • 2021-12-26
        • 2019-06-02
        相关资源
        最近更新 更多