首页 > 解决方案 > API 调用中的 GET 方法以保留标头

问题描述

我有一个 asp.net 核心应用程序,我希望将请求标头保留在响应中。我在邮递员的请求上有 3 个标头,

Authorization: "Bearer xxxxx"
azet-Accept: application/json"
azet-UseLatestversion: true

这是我在配置方法中设置的内容,

app.Use(
        async (context, next) =>
        {
            context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
            context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'");
            context.Response.Headers.Add("Referrer-Policy", "no-referrer");
            context.Response.Headers.Add(
                "Feature-Policy",
                "accelerometer 'none'; camera 'none'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; payment 'none'; usb 'none'");
            context.Response.Headers.Add("X-Frame-Options", "DENY");
            await next();
        });

    app.UseHttpsRedirection();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(
        endpoints =>
        {
            endpoints.MapControllers();
        }); 

我希望在响应中返回像 azet-UseLatestversion 这样的标头

有任何想法吗?

谢谢

[HttpGet]
[Route("{apiPath}/{*requestUri}")]
public async Task<IActionResult> GetAsync(string apiPath, string requestUri = "")
{
    var queryString = this.Request.QueryString.Value;

    var headers = this.Request
        .Headers
        .ToDictionary(x => x.Key, y => y.Value.FirstOrDefault());

    var response = await this.proxy.GetAsync(
                apiPath, requestUri, queryString, headers, this.GetUserScopes());

    this.logger.LogInformation(
                $"GET statement received from {apiPath} {requestUri} {queryString} {DateTime.Now}.");

    var test = response.Content;

    if (response.HttpStatus != HttpStatusCode.OK)
    {
        this.logger.LogError($"{apiPath} {requestUri} {queryString} {response.HttpStatus}: {response.Content}");

        return this.StatusCode((int)response.HttpStatus, ErrorResponse.GetDefaultMessageForStatusCode((int)response.HttpStatus));
    }
     return this.Content(response.Content?.ToString(), response.ContentType);
 }

标签: apiasp.net-coreresponse-headers

解决方案


我希望将请求标头保留在响应中

这是一个工作演示:

app.Use(
    async (context, next) =>
    {
        foreach (var header in context.Request.Headers)
        {
            if(!header.Key.Contains(":"))
            {
                context.Response.Headers.Add(header.Key, header.Value.ToString());
            }
        }           
        await next();
    });

结果: 在此处输入图像描述


推荐阅读