从角度12将类对象发送到asp.net core web api http get方法

Posted

技术标签:

【中文标题】从角度12将类对象发送到asp.net core web api http get方法【英文标题】:Sending class objet to asp.net core web api http get method from angular 12 【发布时间】:2021-12-21 06:44:51 【问题描述】:

我有一个如下的 web api 方法 `

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase

    private readonly ISearchService _searchService;

    public TestController(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; 
     
`

问题:

我想从 Angular 12 向上面的 Http Get 操作方法发送一个 SearchViewModel 类类型的对象。

我可以通过 [FromBody] 装饰 search 参数来使用 HttpPost 来实现这一点。但是有人可以告诉我如何使用 HttpGet 来做到这一点。

提前致谢。

【问题讨论】:

【参考方案1】:

HttpGet 无法发布正文。所以你不能用 HTTP get 方法传递一个对象。但是您可以传递 URL 查询参数,然后稍后在控制器中捕获它们。

例如您可以通过查询参数传递这些数据。那么你的 url 可能是这样的,带有查询参数。

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

然后你可以像这样在 c# 中捕获参数。

public IActionResult YourAction([FromQuery(Name = "ProductId")] string productId,[FromQuery(Name = "StatusId")] string statusId, [FromQuery(Name = "ItemId")] string itemId)

    // do whatever with those params

【讨论】:

以上是关于从角度12将类对象发送到asp.net core web api http get方法的主要内容,如果未能解决你的问题,请参考以下文章