坑:1 同步也异步问题;2 乱码问题 ;3 参数问题
HttpClient 作为发送方传递参数时,接收方为WebApi,此时有多种接收方法
1:直接用实体接收,适用于多参数
2:用System.Web.HttpContext.Current.Request.QueryString[“参数名”].ToString();来接收
下面是接收方的代码:
using System.Web.Http;
using System.Web.Http.Cors;
namespace WebApplication1.Controllers
{
[EnableCors("*", "*", "GET, POST, PUT, DELETE, OPTIONS")]
public class HomeController : ApiController
{
[HttpGet,Route("api/Home/Get")]
public IHttpActionResult Get(string name)
{
return Ok(name);
}
[HttpPost, Route("api/Home/Post")]
public IHttpActionResult Post([FromBody] model model)
{
return Ok(model.name);
}
public static string GetRequsetForm(string key, string defaultVal)
{
if (System.Web.HttpContext.Current.Request.Form[key] == null)
return defaultVal;
return System.Web.HttpContext.Current.Request.Form[key].ToString();
}
public static string GetRequsetQueryString(string key, string defaultVal)
{
if (System.Web.HttpContext.Current.Request.QueryString[key] == null)
return defaultVal;
return System.Web.HttpContext.Current.Request.QueryString[key].ToString();
}
}
public class model
{
public string name { get; set; }
}
}
下面是HttpClient代码,只是简单的实现功能,并没有进行封装
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace TestApp
{
class Program
{
static void Main(string[] args)
{
Get();
}
private static async void GetAsync()
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new System.Uri("http://localhost:6942/api/Home/Post");
try
{
HttpResponseMessage response = await httpClient.GetAsync("?name='你好'&age='12'");
response.EnsureSuccessStatusCode();
string resultStr = await response.Content.ReadAsStringAsync();
Console.WriteLine(resultStr);
}
catch (Exception ex)
{
throw;
}
// 创建一个异步GET请求,当请求返回时继续处理(Continue-With模式)
}
private static void Get()
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new System.Uri("http://localhost:6942/api/Home/Get");
HttpResponseMessage response = httpClient.GetAsync("?name=你好&age=12").Result;
response.EnsureSuccessStatusCode();
string resultStr = response.Content.ReadAsStringAsync().Result;
var str = JsonConvert.DeserializeObject(resultStr);
Console.OutputEncoding = Encoding.UTF8;
Console.WriteLine(str);
}
private static void Post()
{
string Uri = "http://localhost:6942/api/Home/Post";
HttpClient httpClient = new HttpClient();
HttpContent postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"name", "dong"}
});
HttpResponseMessage response = httpClient.PostAsync(Uri,postContent).Result;
response.EnsureSuccessStatusCode();
string resultStr = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(resultStr);
}
}
}