【问题标题】:Sending class objet to asp.net core web api http get method from angular 12从角度12将类对象发送到asp.net core web api http get方法
【发布时间】: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 来做到这一点。

提前致谢。

【问题讨论】:

    标签: angular webapi


    【解决方案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
    }
    

    【讨论】:

      猜你喜欢
      • 2023-02-04
      • 2019-06-26
      • 2016-05-31
      • 2018-12-19
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      • 2020-11-01
      • 2018-04-23
      相关资源
      最近更新 更多