How to build a query string for a URL in C#?

前端 未结 30 2513
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  温柔的废话
    2020-11-22 02:24

    The query string can be added to a URL by:

    1. create a name value collection object
    2. add the query string items and their values to this object
    3. encode this name value collection object to the url the code is provided in the below link

    https://blog.codingnovice.com/blog

    public ActionResult Create()
    {
        //declaring name value collection object
        NameValueCollection collection = new NameValueCollection();
    
        //adding new value to the name value collection object
        collection.Add("Id1", "wwe323");
        collection.Add("Id2", "454w");
        collection.Add("Id3", "tyt5656");
        collection.Add("Id4", "343wdsd");
    
        //generating query string
        string url = GenerateQueryString(collection);
    
        return View();
    }
    
    private string GenerateQueryString(NameValueCollection collection)
    {
        var querystring = (
            from key in collection.AllKeys
            from value in collection.GetValues(key)
            select string.Format("{0}={1}",
                HttpUtility.UrlEncode(key),
                HttpUtility.UrlEncode(value))
        ).ToArray();
        return "?" + string.Join("&", querystring);
    }
    

提交回复
热议问题