简体   繁体   中英

Sending class objet to asp.net core web api http get method from angular 12

I've a web api method like below `

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
    private readonly ISearchService _searchService;

    public RequestController(IRequestService searchService)
    {
        _searchService = searchService;
    }

    [HttpGet, Route("search")]
    public List<ResponseViewModel> search([FromBody] SearchViewModel search)
    {
        return _searchService.GetSearchResults(search);
    }
}`

SearchViewModel.cs

`public class SearchViewModel
     {
          public int ProductId { get; set; }     
          public int StatusId { get; set; }
          public int ItemId  { get; set; }
     }
`

Question:

I wanted to send an object of type SearchViewModel class to the above Http Get action method from angular 12.

I can be able to achieve this with HttpPost by decorating search parameter with [FromBody] . But can someone please tell me how to do this with HttpGet .

Thanks in advance.

HttpGet cant post a body. So you cant pass an object with HTTP get method. But you can pass URL query params then catch them later in the controller.

such as you can pass those data through query params. then your url could be like this with query params.

http://yourbaseurl/search?ProductId=1&StatusId=34&ItemId=190

then you can catch the params in c# like this.

public IActionResult YourAction([FromQuery(Name = "ProductId")] string productId,[FromQuery(Name = "StatusId")] string statusId, [FromQuery(Name = "ItemId")] string itemId)
{
    // do whatever with those params
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM