【问题标题】:Concatenate URL with variable in C#在 C# 中将 URL 与变量连接起来
【发布时间】:2020-01-28 12:09:24
【问题描述】:

我正在尝试将 URL 与变量连接起来,然后是 URL 的“其余部分”。

是这样的:

variableName = "1234";

....

var requestMessage = new HttpRequestMessage(HttpMethod.Get, _configuration["MY_BASE_URL" + variableName + "/theRestOfTheUrl"]);

其中“MY_BASE_URL”作为变量保存为:"http://mytestsite.com/users/"

但是当我这样做时,我得到了错误:

"error":"提供的请求 URI 无效。请求 URI 必须是绝对 URI 或必须设置 BaseAddress。

我做错了什么?刚刚通过时:

var requestMessage = new HttpRequestMessage(HttpMethod.Get, _configuration["MY_BASE_URL"]);

我将“MY_BASE_URL”命名为“http://mytestsite.com/users/1234/theRestOfTheUrl”我没有收到任何错误,但我也可以添加变量名 + 之后的内容,可以选择让变量名是动态的 - 因此我不能把它作为一个完整的硬编码字符串。

【问题讨论】:

  • 创建一个变量并尝试从_configuration创建MY_BASE_URL" + variableName + "/theRestOfTheUrl

标签: c# url httprequest uri


【解决方案1】:

_configuration["MY_BASE_URL"] 是一个配置变量,它返回您的基本 URL,即 http://mytestsite.com/users/,现在您需要将变量值附加到它,然后是硬编码字符串 /theRestOfTheUrl

不要在_configuration键中写所有内容,而是使用string interpolation写它

试试

string url = $"{_configuration["MY_BASE_URL"]}{variableName}/theRestOfTheUrl";
Console.WriteLine(url); // http://mytestsite.com/users/1234/theRestOfTheUrl

你的代码看起来像

variableName = "1234";

....

string url = $"{_configuration["MY_BASE_URL"]}{variableName}/theRestOfTheUrl";
var requestMessage = new HttpRequestMessage(HttpMethod.Get, url);

POC:.net Fiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 1970-01-01
    • 2016-06-26
    • 1970-01-01
    • 2015-10-07
    • 2011-05-13
    • 2014-03-19
    相关资源
    最近更新 更多