我尝试使用HttpClient向api发送数据,但参数I&m; m发送保持接收为0.
我在这里做错了什么?这是我第一次使用HttpClient,所以我很可能混合了一些东西或者犯了一些菜鸟错误。
路径是正确的,我可以从Postman获得结果。
代码I使用的是这个;
static async Task GetActivityList()
{
string uri = "/api/ExtraNet/GetActivityList";
HttpClient client = new HttpClient();
int SalesPersonId = 553;
string token = my token value is here;
client.BaseAddress = new Uri("http://localhost:16513/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var postData = "{\"SalesPersonId=\":\""+SalesPersonId+"\"}";
var stringContent = new StringContent( "{\"SalesPersonId=\":\"" + SalesPersonId + "\"}", Encoding.UTF8, "application/json") ;
var content = new StringContent(postData, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:16513/api/ExtraNet/GetActivityList", stringContent);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
}
答案 0 :(得分:0)
我设法以这种方式发送参数
string uri = "/api/ExtraNet/GetActivityList";
HttpClient client = new HttpClient();
int SalesPersonId = 553;
string token = "";
client.BaseAddress = new Uri("http://localhost:16513/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
var stringContent = new FormUrlEncodedContent(new[] {
new KeyValuePair<string,string>("SalesPersonId","553")
});
var response = await client.PostAsync(uri, stringContent);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
将参数发送为FormUrlEncodedContent
就可以了。