如何在c#中处理url中的逗号

时间:2013-06-13 21:34:06

标签: c# http url

我的网址字符串是

https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A B C \,LLC,D E F \,LLC& Billing_Code = 11,12& fromDateTime = 2013-05-13& toDateTime = 2013-06-13”

如果我在IE中复制并运行,它将返回一些数据。 但是c#中的相同字符串给我一个错误的请求异常。 这是我的c#代码,我想我必须错过一些东西。谢谢

    public void GetDataAsyn(string m_strUrl)
    {
        var username = m_strEmail;
        var password = m_strPassword;

        var uri = new Uri(m_strUrl);            

        var credentialCache = new CredentialCache();
        credentialCache.Add(uri, "Basic", new NetworkCredential(username, password));
        var httpRequest = (HttpWebRequest)WebRequest.Create(uri);
        httpRequest.Method = "GET";
        httpRequest.ContentType = "application/json";
        httpRequest.UseDefaultCredentials = true;
        httpRequest.Accept = Constants.CONTENT_TYPE_TEXT_CSV;
        httpRequest.UserAgent = Helper.GetUserAgent();
        Helper.SetProxyIfNeeded(httpRequest, uri);
        httpRequest.Headers.Add("Authorization", Helper.GetAuthHeader(username, password));

        ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
        httpRequest.BeginGetResponse(GetResponseCallback, new object[] { httpRequest });
    }

    private void GetResponseCallback(IAsyncResult asyncResult)
    {
        try
        {
            var obj = (object[])asyncResult.AsyncState;
            var request = (HttpWebRequest)obj[0];
            var response = request.EndGetResponse(asyncResult);
            Stream responseStream = response.GetResponseStream();
            if (responseStream != null)
            {
                var streamReader = new StreamReader(responseStream);
                ReturnedData = streamReader.ReadToEnd();
            }

            ....do something with ReturnedData
        }
        catch (Exception ex)
        {
            Helper.LogError(ex);
        }
    }

1 个答案:

答案 0 :(得分:1)

我将在黑暗中拍摄,因为您没有告诉我们您如何将您的网址分配给m_strUrl

很可能你收到了错误的请求,因为C#中的\字符是一个转义。

要解决此类问题,您必须要逃避\这样的\\

或者更简洁的方法是使用@符号并使字符串成为文字。

如果您提供的示例中的\是网址的一部分(不是转义字符),则以下是您的文字网址字符串:

    string m_strUrl =  @"https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A%20B%20C\,%20LLC,D%20E%20F\,%20LLC&Billing_Code=11,12&fromDateTime=2013-05-13&toDateTime=2013-06-13";

如果您已经尝试使用\来删除逗号,那么您的字符串将如下所示。

    string m_strUrl = @"https://MyCom.Produect.App.ResourcePath/ts?Customer_Account=A%20B%20C,%20LLC,D%20E%20F,%20LLC&Billing_Code=11,12&fromDateTime=2013-05-13&toDateTime=2013-06-13";