You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从RestSharp响应中获取Location请求头?

解决RestSharp无法获取Location响应头的问题

核心问题分析

你遇到的问题主要出在三个方面:状态码判断逻辑、头名称匹配方式,以及RestSharp对响应头的封装处理。Location响应头通常伴随3xx重定向状态码返回,但你的代码只判断了2xx的“成功”响应;另外HTTP头名称不区分大小写,硬编码匹配可能失效;部分场景下RestSharp的封装层会隐藏底层响应头,需要直接访问原始响应对象。

具体解决方案

1. 修正状态码判断逻辑

Location头仅在3xx重定向响应中存在,默认response.IsSuccessful只识别2xx状态码,需改为判断3xx范围:

if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
{
    // 提取Location头的逻辑
}

2. 忽略大小写匹配头名称

HTTP头名称不区分大小写,用忽略大小写的方式匹配避免因大小写差异找不到头:

string location = response.Headers
    .FirstOrDefault(x => string.Equals(x.Name, "Location", StringComparison.OrdinalIgnoreCase))?
    .Value?.ToString();

3. 直接访问底层HTTP响应对象

如果RestSharp封装层未暴露Location头,可通过response.ResponseMessage获取原始响应,直接提取Location:

if (response.ResponseMessage != null)
{
    var locationUri = response.ResponseMessage.Headers.Location;
    location = locationUri?.ToString();
}

4. 显式指定请求内容类型

部分授权服务器要求表单格式的请求,显式指定Content-Type确保请求格式正确:

request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

完整修改后的代码示例

static string GetAuthCode(string authUri, string clientId, string scope, Guid state, string callbackUri)
{
    var options = new RestClientOptions(authUri)
    {
        FollowRedirects = false,
        MaxTimeout = -1
    };
    var client = new RestClient(options);

    var request = new RestRequest("", Method.Post);
    request.AddHeader("Content-Type", "application/x-www-form-urlencoded");

    request.AddParameter("client_id", clientId);
    request.AddParameter("response_type", "code");
    request.AddParameter("scope", scope);
    request.AddParameter("state", state);
    request.AddParameter("username", "XXXXXXXXX", true);
    request.AddParameter("password", "XXXXXXXXX", true);
    request.AddParameter("redirect_uri", callbackUri);

    RestResponse response = client.Execute(request);

    if ((int)response.StatusCode >= 300 && (int)response.StatusCode < 400)
    {
        string location = response.Headers
            .FirstOrDefault(x => string.Equals(x.Name, "Location", StringComparison.OrdinalIgnoreCase))?
            .Value?.ToString();

        if (string.IsNullOrEmpty(location) && response.ResponseMessage != null)
        {
            var locationUri = response.ResponseMessage.Headers.Location;
            location = locationUri?.ToString();
        }

        return location ?? throw new Exception("未找到Location响应头");
    }
    else if (response.IsSuccessful)
    {
        throw new Exception("请求未返回重定向响应,无法获取Location头");
    }
    else
    {
        throw new Exception($"请求失败:{response.Content}");
    }
}

内容的提问来源于stack exchange,提问作者user2148983

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 23:50:28