如何在 C# 中使用接受一个 FromUri 参数和第二个 FromBody 参数的 Web API 2 GET 命令。我不知道如何在 GET 命令中发送正文,我需要使用 POST 命令吗?但如何呢?下面是我到目前为止编写的代码。谢谢。
API代码
[HttpGet]
[ResponseType(typeof(IEnumerable<Student>))]
public IHttpActionResult Find([FromUri]string searchText,[FromBody]SearchType searchType)
{
//EF code to get data from DB
using (handler)
{
return Ok(handler.Find(searchText, searchType));
}
}
Http客户端代码
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
string aSearchText ="John";
SearchType aSearchType = SearchType.Name; //this is enum
Task<HttpResponseMessage> responseTask = client.GetAsync($"api/Student/{aSearchText}");
responseTask.Wait();
////////////////////
/// Code missing how to send "aSearchType" as a body in Get Command?
////////////////////
var ListTask = responseTask.Content.ReadAsAsync<IEnumerable<Student>>();
ListTask.Wait();
IEnumerable<Student> list = ListTask.Result;
foreach(Student s in list)
{
Console.WriteLine(s.Name);
}
}
慕慕森
相关分类