如何在 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); }}
1 回答

慕慕森
TA贡献1856条经验 获得超17个赞
您可以将参数从 body 传递到 HttpGet 操作,但这不符合逻辑。
您可以使用 HttpPost 从正文发送数据。
[HttpPost]
[ResponseType(typeof(IEnumerable<Student>))]
public IHttpActionResult Find([FromBody]SearchType searchType,[FromUri]string searchText)
{
//EF code to get data from DB
using (handler)
{
return Ok(handler.Find(searchText, searchType));
}
}
string aSearchText ="John";
SearchType aSearchType = SearchType.Name; //this is enum
Task<HttpResponseMessage> responseTask = client.PostAsJsonAsync($"api/Student/{aSearchText}",aSearchType );
responseTask.Wait();
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消