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

如何在 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);

     }

}


噜噜哒
浏览 91回答 1
1回答

慕慕森

您可以将参数从 body 传递到 HttpGet 操作,但这不符合逻辑。您可以使用 HttpPost 从正文发送数据。[HttpPost][ResponseType(typeof(IEnumerable<Student>))]public IHttpActionResult Find([FromBody]SearchType searchType,[FromUri]string searchText){&nbsp; &nbsp; //EF code to get data from DB&nbsp; &nbsp; using (handler)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return Ok(handler.Find(searchText, searchType));&nbsp; &nbsp; }}string aSearchText ="John";&nbsp; &nbsp; &nbsp;SearchType aSearchType = SearchType.Name; //this is enum&nbsp; &nbsp; &nbsp;Task<HttpResponseMessage> responseTask = client.PostAsJsonAsync($"api/Student/{aSearchText}",aSearchType );&nbsp; &nbsp; &nbsp;responseTask.Wait();
打开App,查看更多内容
随时随地看视频慕课网APP