簡體   English   中英

通過字典 <string,string> Web API中的參數

[英]Pass a Dictionary<string,string> parameter in web api

我正在嘗試將Dictionary<string,string>對象作為參數傳遞給我的Web api方法,但是如果我檢查日志文件,則總是以0計數:

Web API方法:

[HttpPost]
[ActionName("SendPost")]
public void SendPost([FromBody] Dictionary<string,string> values)
{
    using (var sw = new StreamWriter("F:\\PostTest.txt", true))
    {
        sw.WriteLine("Number of items in the dictionary - " + values.Count);
    }
}

調用Web API的邏輯:

public HttpResponseMessage Send(string uri, string value)
{
    HttpResponseMessage responseMessage = null;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(URI);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var content = new FormUrlEncodedContent
            (
                new Dictionary<string, string> { { "value", value } }
            );

        responseMessage = client.PostAsync(uri, content).Result;
    }
    return responseMessage;
}

問題在於您所說的內容類型為“ application / json”,但您將其作為FormUrlEncodedContent傳遞了。 您需要使用StringContent並將您自己的內容序列化為JSON,或者可以使用擴展方法HttpClientExtensions.PostAsJsonAsync為您將內容序列化為JSON:

public async Task<HttpResponseMessage> SendAsync(string uri, string value)
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri(URI);
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
                        new MediaTypeWithQualityHeaderValue("application/json"));

        return await client.PostAsJsonAsync(uri, content);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM