typescript 在ASP.NET内核和Angular中,如何在向后端传递http参数的同时从后端获取http标头?

aamkag61  于 2023-01-27  发布在  TypeScript
关注(0)|答案(2)|浏览(93)

我正在使用Angular 15和ASP.NET Core 5。当pageSizepageIndex作为参数传递给后端时,我从后端获得分页项。
接收pageSizepageIndex参数的action方法然后将分页的项以及totalCount发送到前端。
代码如下:

[HttpGet("getPagedCommodities")]
public async Task<IActionResult> GetPagedCommodities([FromQuery] PagingParameters pagingParameters)
{
    try
    { 
        var commodities = await _repository.Commodity.GetAllCommoditiesAsync();
        var totalCount = commodities.Count();
                
        var pagedCommodities = await _repository.Commodity.GetPagedCommoditiesAsync(pagingParameters);
                
        Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(totalCount));                

        return Ok(pagedCommodities);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}

在前端,这是获取分页项的方法:

getPagedCommodities(pageSize: number, pageNumber: number): Observable<CommodityForList[]> {
    let params: HttpParams = new HttpParams();
    params = params.append('pageSize', pageSize);
    params = params.append('pageNumber', pageNumber);
    
    let httpOptions = {
      params: params
    };
    return this.http.get<CommodityForList[]>(this.baseUrl + '/getPagedCommodities/', httpOptions);
      
  }

如何读取服务器发送的totalCount http头参数?
谢谢你的帮助。

fdbelqdn

fdbelqdn1#

如何访问API响应的标头参数

我现在将您的代码集成到我自己的Angular/ .NET项目中,并最终找到了一个可以工作的代码:

后端:启动.cs

我必须将X-Pagination添加到CORS策略中,否则它将始终为undefined. Click here to read why this is needed

services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .WithExposedHeaders("X-Pagination"); // I had to add this line
    });
});

后端:控制器方法

我不得不将输入参数从PagingParameters pagingParameters更改为[FromQuery] int pageSize, [FromQuery] int pageNumber

[HttpGet("getPagedCommodities")]
public async Task<IActionResult> GetPagedCommodities([FromQuery] int pageSize, [FromQuery] int pageNumber)
{
    try
    { 
        var commodities = await _repository.Commodity.GetAllCommoditiesAsync();
        var totalCount = commodities.Count();
                
        var pagedCommodities = await _repository.Commodity.GetPagedCommoditiesAsync(pagingParameters);
                
        Response.Headers.Add("X-Pagination", JsonConvert.SerializeObject(totalCount));                

        return Ok(pagedCommodities);
    }
    catch
    {
        return StatusCode(500, "Internal server error");
    }
}

前端:服务方法

通过添加observe: 'response',将授予对HttpResponse<YourJsonObject>的访问权限,然后您可以通过response.headers.get("Header-Key")获取头值。
我还不得不改变组装httpOptions的方式(这是this.http.get的第二个参数)。

getPagedCommodities(pageSize: number, pageNumber: number): Observable<{commodities: CommodityForList[]; totalCount: number}> {

    const params: HttpParams = new HttpParams()
                                .append('pageSize', pageSize)
                                .append('pageNumber', pageNumber);

    const url = `${this.baseUrl}/getPagedCommodities/`;

    return this.http.get<CommodityForList[]>(url, { observe: 'response', params })
        .pipe(
            map(response => {

            // Access 'total count' in header:
            const totalCount = response?.headers?.get('X-Pagination');
            const parsedTotalCount = +(totalCount ?? 0);

            return { commodities: response?.body ?? [],
                     totalCount: parsedTotalCount };
            })
        );
}

最后,我能够访问返回值,如下所示:

this.getPagedCommodities(0, 1).subscribe(
    res => {
        console.log('Commodities-Array:', res.commodities);
        console.log('Total count:', res.totalCount);
    }
);
kcugc4gi

kcugc4gi2#

您可以将设置observe: 'response'传递给http get以观察整个响应,而不仅仅是主体。

this.http.get(myUrl, {
  observe: 'response',
  params
}).subscribe(response => console.log(response))

现在你得到的不是主体,而是整个响应,其中headersbody是响应的属性:

{
  headers: {
    totalCount: 123
  },
  status: 200,
  body: {}
}

相关问题