C# 在URI中动态替换参数
我已经编写了一个实用类函数,它接受一个URI和一个ID,该ID使用提供的URI创建一个HTTPClientC# 在URI中动态替换参数,c#,.net,dynamic,uri,dotnet-httpclient,C#,.net,Dynamic,Uri,Dotnet Httpclient,我已经编写了一个实用类函数,它接受一个URI和一个ID,该ID使用提供的URI创建一个HTTPClient private async Task<T> GetUriScopedResource<T>(string uri, int id) { var client = _httpClientFactory.CreateClient(_baseUri); client.BaseAddress = new Uri(_baseUr
private async Task<T> GetUriScopedResource<T>(string uri, int id)
{
var client = _httpClientFactory.CreateClient(_baseUri);
client.BaseAddress = new Uri(_baseUri);
var result = await client.GetAsync($"{uri}{id}");
return await DeserialiseContentAsync<T>(result);
}
但是,我的需求发生了变化,我有一个控制器方法,如下所示:
"api/Employee/{id}/accounts"
如何修改
client.GetAsync($"{relativeUri}{id}");
要为提供的任何URI动态替换{X}吗?URIBuilder能否实现这一预期功能
任何帮助都会很好 如果您只是在寻找漂亮的结构化URL构建,(免责声明:我是作者)可能会有所帮助。它有一个静态的
Url.Combine
方法,该方法类似于Path.Combine
对于文件,确保段之间只有1个分隔符:
Url.Combine(_baseUri, relativeUri, id, "accounts")
这是一个非常小的,没有依赖关系
将fluent HTTP、Json.NET(反)序列化、测试功能和智能HttpClient
实例管理添加到组合中。您的示例如下所示:
private Task<T> GetUriScopedResource<T>(string uri, int id)
{
return _baseUri
.AppendPathSegments(uri, id, "accounts")
.GetJsonAsync<T>();
}
私有任务GetUriScopedResource(字符串uri,int-id)
{
返回_baseUri
.AppendPathSegments(uri,id,“帐户”)
.GetJsonAsync();
}
AppendPathSegments
基本上为您提供了Url。组合作为string
的流畅扩展方法。考虑到这一点,它可能需要处理传递给函数的多个参数。例如,URI可能是“api/Employee/{id}/accountsettings/{accountId}”,如果URI总是在更改,则必须手动构建此URL,可能是预定义的URL,其中包含{0)
{1}
,并使用string.Format填充它们
private Task<T> GetUriScopedResource<T>(string uri, int id)
{
return _baseUri
.AppendPathSegments(uri, id, "accounts")
.GetJsonAsync<T>();
}