【发布时间】:2019-07-22 12:01:56
【问题描述】:
如何在 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));
}
}
HttpClient 代码
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);
}
}
【问题讨论】:
-
我会推荐阅读RFC 2616 Sc9.3。当然,这只是一个建议。规范并没有说你不能。它说你不应该。
标签: c# asp.net-web-api2 httpclient