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

如何在Axum处理器中设置响应Header?含Content-Type及自定义头

在Axum中为into_response()生成的响应设置Header

1. 直接修改响应Header集合

通过thing.into_response()得到Response实例后,调用headers_mut()获取可变Header引用,即可添加或修改标准/自定义Header:

use axum::{response::IntoResponse, http::header};

async fn handler() -> impl IntoResponse {
    // 生成基础响应
    let mut response = "Hello, World!".into_response();
    
    // 设置Content-Type为JSON格式
    response.headers_mut().insert(
        header::CONTENT_TYPE,
        "application/json; charset=utf-8".parse().unwrap(),
    );
    
    // 添加自定义Header
    response.headers_mut().insert(
        "X-Custom-Header",
        "My-Custom-Value".parse().unwrap(),
    );
    
    response
}

2. 用TypedHeader安全处理标准Header

Axum提供的TypedHeader可以避免手动解析字符串的错误,更安全地设置标准HTTP Header(需开启typed-headers特性):
先在Cargo.toml中添加依赖:

axum = { version = "0.7", features = ["typed-headers"] }

使用示例:

use axum::{
    response::{IntoResponse, Response},
    headers::{ContentType, HeaderMapExt},
};

async fn handler() -> impl IntoResponse {
    let mut response = "{\"message\": \"Hello\"}".into_response();
    
    // 安全设置Content-Type为JSON
    response.headers_mut().typed_insert(ContentType::json());
    
    // 设置其他标准Header,比如缓存控制
    response.headers_mut().typed_insert(
        axum::headers::CacheControl::new().with_max_age(std::time::Duration::from_secs(3600))
    );
    
    // 自定义Header仍用普通insert方法
    response.headers_mut().insert(
        "X-Request-ID",
        "abc123".parse().unwrap(),
    );
    
    response
}

3. 链式调用with_header简化写法

借助ResponseExt trait的with_header方法,实现链式修改Header:

use axum::{
    response::{IntoResponse, ResponseExt},
    http::header,
};

async fn handler() -> impl IntoResponse {
    "Hello, World!".into_response()
        .with_header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
        .with_header("X-Custom-Header", "Custom-Value")
}

注:若Header值解析失败,with_header会返回InvalidHeaderValue错误,可使用with_header_if_valid避免 panic。

4. 在自定义类型的IntoResponse实现中预设Header

如果thing是自定义类型,可以直接在它的IntoResponse实现中设置固定Header,每次调用into_response()都会自动带上:

use axum::{response::IntoResponse, http::Response, http::header};

struct MyJsonData {
    content: String,
}

impl IntoResponse for MyJsonData {
    fn into_response(self) -> Response {
        let mut response = self.content.into_response();
        response.headers_mut().insert(
            header::CONTENT_TYPE,
            "application/json".parse().unwrap(),
        );
        response.headers_mut().insert(
            "X-My-Header",
            "Fixed-Value".parse().unwrap(),
        );
        response
    }
}

async fn handler() -> impl IntoResponse {
    MyJsonData { content: "{\"key\": \"value\"}".to_string() }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:22:15