爲什麼在URI中傳遞數據看起來多餘? HTTP規範說GET方法不是使用正文中發送的內容。這主要是爲了便於緩存能夠緩存僅基於URI,方法和頭的響應。要求高速緩存解析消息的主體以識別資源將是非常低效的。
這裏有一個基本的擴展方法,將做繁重的工作適合你,
public static class UriExtensions
{
public static Uri AddToQuery<T>(this Uri requestUri,T dto)
{
Type t = typeof (T);
var properties = t.GetProperties();
var dictionary = properties.ToDictionary(info => info.Name,
info => info.GetValue(dto, null).ToString());
var formContent = new FormUrlEncodedContent(dictionary);
var uriBuilder = new UriBuilder(requestUri) {Query = formContent.ReadAsStringAsync().Result};
return uriBuilder.Uri;
}
}
,並假設你有一個DTO這樣,
public class Foo
{
public string Bar { get; set; }
public int Baz { get; set; }
}
,你可以使用它像這樣。
[Fact]
public void Foo()
{
var foo = new Foo()
{
Bar = "hello world",
Baz = 10
};
var uri = new Uri("http://example.org/blah");
var uri2 = uri.AddToQuery(foo);
Assert.Equal("http://example.org/blah?Bar=hello+world&Baz=10", uri2.AbsoluteUri);
}
您可以提供關於您的API的更多詳細信息 - 第一個用於GET請求的對象是什麼?通常,查詢字符串用於過濾GET請求以檢索與特定查詢匹配的數據。 –