expression
Axum: reject duplicate form fields
A form can repeat a field name. Decide explicitly whether repeats are allowed. This endpoint accepts exactly one title, rejects unknown parts, and never silently replaces an earlier value. In-memory standalone Cargo example. Expected stdout (not executed): 400 Common mistake: Accepting whichever duplicate value happens to be processed last.
Formal Syntax & Structure
rust syntaxrust
if seen { return Err(StatusCode::BAD_REQUEST); }Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::{extract::Multipart, routing::post, http::header}; async fn upload(mut form: Multipart) -> Result<String, StatusCode> { let mut title = None; while let Some(field) = form.next_field().await.map_err(|e| e.status())? { if field.name() != Some("title") || title.is_some() { return Err(StatusCode::BAD_REQUEST); } title = Some(field.text().await.map_err(|e| e.status())?); } title.ok_or(StatusCode::BAD_REQUEST) } let app = Router::new().route("/upload", post(upload)) .layer(axum::extract::DefaultBodyLimit::max(1024)); let req = Request::builder().method("POST").uri("/upload") .header(header::CONTENT_TYPE, "multipart/form-data; boundary=demo") .body(Body::from("--demo\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nFirst\r\n--demo\r\nContent-Disposition: form-data; name=\"title\"\r\n\r\nSecond\r\n--demo--\r\n")).unwrap(); let r = app.oneshot(req).await.unwrap(); println!("{}", r.status().as_u16()); let b = to_bytes(r.into_body(), 256).await.unwrap(); if !b.is_empty() { println!("{}", String::from_utf8_lossy(&b)); }}