用参数创建自己的Uri

时间:2015-01-18 20:14:28

标签: c# web-services windows-phone-8.1 uri

我尝试使用一些参数创建自己的Uri。我写了这个,但它不起作用:

string url = "http://arweb.elwin013.com/api/rest/tag/getNearestTags?latitude=" + lat.ToString("0.00000") + "&longitude=" + lon.ToString("0.00000") + "&distance=100000";
var response = await client.GetAsync(new Uri(url));

知道为什么吗?

1 个答案:

答案 0 :(得分:2)

您的问题是ToString方法将数字转换为其中包含,的字符串。这会破坏服务器,使其返回http-500错误。

要修复您的代码,请确保使用ToString重载接受InvariantCulture,如下所示:

decimal lat = 1.25M;
decimal lon = 2.25M;
string url = "http://arweb.elwin013.com/api/rest/tag/getNearestTags?latitude=" + 
   lat.ToString("0.00000",CultureInfo.InvariantCulture) + 
   "&longitude=" + 
   lon.ToString("0.00000",CultureInfo.InvariantCulture) + 
   "&distance=100000";
var u = new Uri(url);
Debug.WriteLine(u); // use this to verify how your real Url would look
var response = await client.GetAsync(u);

您也可以使用UriBuilder类构建您的Uri:

var builder = new UriBuilder {
     Scheme = "http"
     , Host ="arweb.elwin013.com"
     , Path = "api/rest/tag/getNearestTags"
     , Query = String.Format(
        CultureInfo.InvariantCulture,
        "latitude={0:0.00000}&longitude={1:0.00000}&distance=100000",
        lat, 
        lon)
   };
var response = await client.GetAsync(builder.Uri);

如果你不得不建立复杂的Uri,那可能会让事情变得更有条理,更易于维护。