如何使用接受 FromBody 参数的 API GET 方法

How to Consume API GET method that accepts FromBody parameter

如何在 C# 中使用 Web API 2 GET 命令接受一个 FromUri 参数和第二个 FromBody 参数。我不知道如何在 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);
     }
}

您可以将参数从正文传递到 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();