最小 API 應用程式中的參數繫結

注意事項

這不是這篇文章的最新版本。 關於目前版本,請參閱本文的 .NET 11 版本。

警告

不再支援此版本的 ASP.NET Core。 如需詳細資訊,請參閱 .NET 和 .NET Core 支持原則。 關於目前版本,請參閱 本文的 .NET 10 版本。

參數繫結是將請求資料轉換為路由處理常式所定義的強型別參數的過程。 繫結來源會決定參數的繫結來源位置。 繫結來源可以是明確或根據 HTTP 方法和參數型別推斷。

支援的繫結來源:

  • 路由值
  • 查詢字串
  • 頁首
  • 主體(JSON 格式)
  • 表單值
  • 由依賴注入提供的服務
  • 自訂

注意事項

C# 聯集類型僅支援作為本文(JSON 格式)。 非正體來源——路由值、查詢字串、標頭和表單值——會綁定字串值而無需 JSON 解析,因此無法派遣到聯合情境。

下列 GET 路由處理常式會使用以下其中一些參數繫結來源:

var builder = WebApplication.CreateBuilder(args);

// Added as service
builder.Services.AddSingleton<Service>();

var app = builder.Build();

app.MapGet("/{id}", (int id,
                     int page,
                     [FromHeader(Name = "X-CUSTOM-HEADER")] string customHeader,
                     Service service) => { });

class Service { }

下表顯示上述範例中所使用參數與關聯繫結來源之間的關聯性。

參數 繫結來源
id 路由值
page 查詢字串
customHeader 標頭
service 由相依性注入提供

例如,給定以下 HTTP 請求:

GET /42?page=3 HTTP/1.1
Host: example.com
X-CUSTOM-HEADER: hello
  • 42 在 /42 中符合路由範本 {id} 的 /{id},並繫結至 id 路由參數。
  • page=3 在 ?page=3 中匹配查詢字串鍵 page,並綁定至 page 參數。
  • X-CUSTOM-HEADER: hello 匹配 [FromHeader(Name = "X-CUSTOM-HEADER")] 標頭屬性並綁定到 customHeader。
  • service 是從相依注入(DI)容器中解析,而非從接收的 HTTP 請求中解析。

HTTP 方法 GET、HEAD、OPTIONS 和 DELETE 不會隱含從本文繫結。 若要從本文 (JSON 格式) 繫結這些 HTTP 方法,請明確繫結[FromBody] 或從 HttpRequest 讀取。

下列範例 POST 路由處理常式會針對 person 參數使用本文 (JSON 格式) 的繫結來源:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapPost("/", (Person person) => { });

record Person(string Name, int Age);

上述範例中的參數全都會自動從要求資料繫結。 為了示範參數繫結所提供的便利性,下列路由處理常式將示範如何直接從要求讀取要求資料:

app.MapGet("/{id}", (HttpRequest request) =>
{
    var id = request.RouteValues["id"];
    var page = request.Query["page"];
    var customHeader = request.Headers["X-CUSTOM-HEADER"];

    // ...
});

app.MapPost("/", async (HttpRequest request) =>
{
    var person = await request.ReadFromJsonAsync<Person>();

    // ...
});

明確參數繫結

屬性可用來明確宣告參數繫結的來源位置。

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// Added as service
builder.Services.AddSingleton<Service>();

var app = builder.Build();


app.MapGet("/{id}", ([FromRoute] int id,
                     [FromQuery(Name = "p")] int page,
                     [FromServices] Service service,
                     [FromHeader(Name = "Content-Type")] string contentType) 
                     => {});

class Service { }

record Person(string Name, int Age);
參數 繫結來源
id 名稱為 id 的路由值
page 具有名稱 "p" 的查詢字串
service 由相依性注入提供
contentType 具有名稱 "Content-Type" 的標頭

來自表單值的明確繫結

[FromForm] 屬性會繫結表單值:

app.MapPost("/todos", async ([FromForm] string name,
    [FromForm] Visibility visibility, IFormFile? attachment, TodoDb db) =>
{
    var todo = new Todo
    {
        Name = name,
        Visibility = visibility
    };

    if (attachment is not null)
    {
        var attachmentName = Path.GetRandomFileName();

        using var stream = File.Create(Path.Combine("wwwroot", attachmentName));
        await attachment.CopyToAsync(stream);
    }

    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Ok();
});

// Remaining code removed for brevity.

另一種作法是使用 [AsParameters] 屬性,搭配其屬性以 [FromForm] 標註的自訂型別。 例如,下列程式碼會從表單值繫結至 NewTodoRequest 記錄結構的屬性:

app.MapPost("/ap/todos", async ([AsParameters] NewTodoRequest request, TodoDb db) =>
{
    var todo = new Todo
    {
        Name = request.Name,
        Visibility = request.Visibility
    };

    if (request.Attachment is not null)
    {
        var attachmentName = Path.GetRandomFileName();

        using var stream = File.Create(Path.Combine("wwwroot", attachmentName));
        await request.Attachment.CopyToAsync(stream);

        todo.Attachment = attachmentName;
    }

    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Ok();
});

// Remaining code removed for brevity.
public record struct NewTodoRequest([FromForm] string Name,
    [FromForm] Visibility Visibility, IFormFile? Attachment);

如需詳細資訊,請參閱本文稍後的 AsParameters 一節。

完整的範例程式碼位於 AspNetCore.Docs.Samples 存放庫中。

來自 IFormFile 和 IFormFileCollection 的安全繫結

使用 IFormFile,即可透過 IFormFileCollection 和 [FromForm] 支援複雜的表單繫結:

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAntiforgery();

var app = builder.Build();
app.UseAntiforgery();

// Generate a form with an anti-forgery token and an /upload endpoint.
app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    var html = MyUtils.GenerateHtmlForm(token.FormFieldName, token.RequestToken!);
    return Results.Content(html, "text/html");
});

app.MapPost("/upload", async Task<Results<Ok<string>, BadRequest<string>>>
    ([FromForm] FileUploadForm fileUploadForm, HttpContext context,
                                                IAntiforgery antiforgery) =>
{
    // Server-side validation. The client-side pattern can be bypassed, so the
    // name must be validated here too.
    if (!MyUtils.IsValidFileName(fileUploadForm.Name))
    {
        return TypedResults.BadRequest("Invalid file name.");
    }

    await MyUtils.SaveFileWithName(fileUploadForm.FileDocument!,
              fileUploadForm.Name!, app.Environment.ContentRootPath);
    return TypedResults.Ok($"Your file with the description:" +
        $" {fileUploadForm.Description} has been uploaded successfully");
});

app.Run();

以 [FromForm] 繫結至要求的參數包含防偽權杖。 處理請求時,系統會驗證防偽權杖。 如需詳細資訊,請參閱使用基本 API 進行防偽。

欲了解更多資訊,請參閱 「最小 API 中的表單綁定」。

完整的範例程式碼位於 AspNetCore.Docs.Samples 存放庫中。

使用相依性注入的參數繫結

當類型被設定為服務時,最小 API 的參數會透過 依賴注入 進行綁定。 不需要將 [FromServices] 屬性明確套用至參數。 在下列程式碼中,這兩個動作都會傳回時間:

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IDateTime, SystemDateTime>();

var app = builder.Build();

app.MapGet("/",   (               IDateTime dateTime) => dateTime.Now);
app.MapGet("/fs", ([FromServices] IDateTime dateTime) => dateTime.Now);
app.Run();

選擇性參數

在路由處理程式中宣告的參數會被視為必要:

  • 如果要求符合路由,則只有在要求中提供所有必要的參數時,路由處理常式才會執行。
  • 無法提供所有必要參數會導致錯誤。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int pageNumber) => $"Requesting page {pageNumber}");

app.Run();
URI 結果
/products?pageNumber=3 3 項已傳回
/products BadHttpRequestException:查詢字串中未提供必要的參數 "int pageNumber"。
/products/1 HTTP 404 錯誤,沒有相符的路由

若要將 pageNumber 設為選用,請將型別定義為選用或提供預設值:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int? pageNumber) => $"Requesting page {pageNumber ?? 1}");

string ListProducts(int pageNumber = 1) => $"Requesting page {pageNumber}";

app.MapGet("/products2", ListProducts);

app.Run();
URI 結果
/products?pageNumber=3 3 項已傳回
/products 已傳回 1 項
/products2 已傳回 1 項

前述的可為 Null 設定與預設值適用於所有來源:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/products", (Product? product) => { });

app.Run();

如果未傳送任何要求主體,上述程式碼會以 null 的 product 呼叫該方法。

注意:如果提供無效資料且參數可為 Null,則路由處理常式不會執行。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int? pageNumber) => $"Requesting page {pageNumber ?? 1}");

app.Run();
URI 結果
/products?pageNumber=3 3 傳回
/products 1 傳回
/products?pageNumber=two BadHttpRequestException:無法從 "two" 繫結參數 "Nullable<int> pageNumber"。
/products/two HTTP 404 錯誤,沒有相符的路由

如需詳細資訊,請參閱繫結失敗一節。

特殊型別

下列型別會在沒有明確屬性的情況下繫結:

  • HttpContext:保存有關目前 HTTP 請求或回應之所有資訊的內容物件:

    app.MapGet("/", (HttpContext context) => context.Response.WriteAsync("Hello World"));
    
  • HttpRequest 和 HttpResponse:HTTP 要求和 HTTP 回應:

    app.MapGet("/", (HttpRequest request, HttpResponse response) =>
        response.WriteAsync($"Hello World {request.Query["name"]}"));
    
  • CancellationToken:與目前 HTTP 要求相關聯的取消權杖:

    app.MapGet("/", async (CancellationToken cancellationToken) =>
        await MakeLongRunningRequestAsync(cancellationToken));
    
  • ClaimsPrincipal:與要求相關聯的使用者,繫結自 HttpContext.User:

    app.MapGet("/", (ClaimsPrincipal user) => user.Identity.Name);
    

將請求本文繫結為 Stream 或 PipeReader

要求主體可繫結為 Stream 或 PipeReader,以有效支援使用者必須處理資料的情境,並:

  • 將資料儲存至 Blob 儲存體,或將資料排入佇列提供者的佇列。
  • 使用工作處理序或雲端函式來處理已儲存的資料。

例如,資料可能會加入佇列至 Azure 佇列儲存體,或儲存在 Azure Blob 儲存體中。

下列程式碼會實作背景佇列:

using System.Text.Json;
using System.Threading.Channels;

namespace BackgroundQueueService;

class BackgroundQueue : BackgroundService
{
    private readonly Channel<ReadOnlyMemory<byte>> _queue;
    private readonly ILogger<BackgroundQueue> _logger;

    public BackgroundQueue(Channel<ReadOnlyMemory<byte>> queue,
                               ILogger<BackgroundQueue> logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var dataStream in _queue.Reader.ReadAllAsync(stoppingToken))
        {
            try
            {
                var person = JsonSerializer.Deserialize<Person>(dataStream.Span)!;
                _logger.LogInformation($"{person.Name} is {person.Age} " +
                                       $"years and from {person.Country}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }
    }
}

class Person
{
    public string Name { get; set; } = String.Empty;
    public int Age { get; set; }
    public string Country { get; set; } = String.Empty;
}

下列程式碼會將要求主體繫結到 Stream:

app.MapPost("/register", async (HttpRequest req, Stream body,
                                 Channel<ReadOnlyMemory<byte>> queue) =>
{
    if (req.ContentLength is not null && req.ContentLength > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // We're not above the message size and we have a content length, or
    // we're a chunked request and we're going to read up to the maxMessageSize + 1. 
    // We add one to the message size so that we can detect when a chunked request body
    // is bigger than our configured max.
    var readSize = (int?)req.ContentLength ?? (maxMessageSize + 1);

    var buffer = new byte[readSize];

    // Read at least that many bytes from the body.
    var read = await body.ReadAtLeastAsync(buffer, readSize, throwOnEndOfStream: false);

    // We read more than the max, so this is a bad request.
    if (read > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // Attempt to send the buffer to the background queue.
    if (queue.Writer.TryWrite(buffer.AsMemory(0..read)))
    {
        return Results.Accepted();
    }

    // We couldn't accept the message since we're overloaded.
    return Results.StatusCode(StatusCodes.Status429TooManyRequests);
});

下列程式碼會顯示完整的 Program.cs 檔案:

using System.Threading.Channels;
using BackgroundQueueService;

var builder = WebApplication.CreateBuilder(args);
// The max memory to use for the upload endpoint on this instance.
var maxMemory = 500 * 1024 * 1024;

// The max size of a single message, staying below the default LOH size of 85K.
var maxMessageSize = 80 * 1024;

// The max size of the queue based on those restrictions
var maxQueueSize = maxMemory / maxMessageSize;

// Create a channel to send data to the background queue.
builder.Services.AddSingleton<Channel<ReadOnlyMemory<byte>>>((_) =>
                     Channel.CreateBounded<ReadOnlyMemory<byte>>(maxQueueSize));

// Create a background queue service.
builder.Services.AddHostedService<BackgroundQueue>();
var app = builder.Build();

// curl --request POST 'https://localhost:<port>/register' --header 'Content-Type: application/json' --data-raw '{ "Name":"Samson", "Age": 23, "Country":"Nigeria" }'
// curl --request POST "https://localhost:<port>/register" --header "Content-Type: application/json" --data-raw "{ \"Name\":\"Samson\", \"Age\": 23, \"Country\":\"Nigeria\" }"
app.MapPost("/register", async (HttpRequest req, Stream body,
                                 Channel<ReadOnlyMemory<byte>> queue) =>
{
    if (req.ContentLength is not null && req.ContentLength > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // We're not above the message size and we have a content length, or
    // we're a chunked request and we're going to read up to the maxMessageSize + 1. 
    // We add one to the message size so that we can detect when a chunked request body
    // is bigger than our configured max.
    var readSize = (int?)req.ContentLength ?? (maxMessageSize + 1);

    var buffer = new byte[readSize];

    // Read at least that many bytes from the body.
    var read = await body.ReadAtLeastAsync(buffer, readSize, throwOnEndOfStream: false);

    // We read more than the max, so this is a bad request.
    if (read > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // Attempt to send the buffer to the background queue.
    if (queue.Writer.TryWrite(buffer.AsMemory(0..read)))
    {
        return Results.Accepted();
    }

    // We couldn't accept the message since we're overloaded.
    return Results.StatusCode(StatusCodes.Status429TooManyRequests);
});

app.Run();
  • 讀取資料時,Stream 和 HttpRequest.Body 是相同的物件。
  • 要求主體預設不會被緩衝。 讀取本文之後,將無法倒轉。 無法重複讀取資料流。
  • Stream 和 PipeReader 無法在基本動作處理常式之外使用,因為基礎緩衝區將會受到處置或重複使用。

使用 IFormFile 和 IFormFileCollection 上傳檔案

在最小 API 中使用IFormFile和IFormFileCollection上傳檔案時,需要進行multipart/form-data編碼。 路由處理常式中的參數名稱必須符合要求中的表單欄位名稱。 最小化 API 不支援在不使用表單編碼的情況下,將整個請求本文直接繫結到 IFormFile 參數。

如果您需要繫結整個要求內文,例如,在使用 JSON、二進位資料或其他內容類型時,請參閱:

下列程式碼會使用 IFormFile 和 IFormFileCollection 來上傳檔案:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapPost("/upload", async (IFormFile file) =>
{
    var tempFile = Path.GetTempFileName();
    app.Logger.LogInformation(tempFile);
    using var stream = File.OpenWrite(tempFile);
    await file.CopyToAsync(stream);
});

app.MapPost("/upload_many", async (IFormFileCollection myFiles) =>
{
    foreach (var file in myFiles)
    {
        var tempFile = Path.GetTempFileName();
        app.Logger.LogInformation(tempFile);
        using var stream = File.OpenWrite(tempFile);
        await file.CopyToAsync(stream);
    }
});

app.Run();

支援使用授權標頭、用戶端憑證或 cookie 標頭的已驗證檔案上傳要求。

使用 IFormCollection、IFormFile 與 IFormFileCollection 繫結至表單

支援使用 IFormCollection、IFormFile 和 IFormFileCollection 繫結表單型參數。 OpenAPI 中繼資料會推斷為表單參數,可支援與 Swagger UI 的整合。

下列程式碼會使用來自 IFormFile 型別的推斷繫結來上傳檔案:

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAntiforgery();

var app = builder.Build();
app.UseAntiforgery();

string GetOrCreateFilePath(string fileName, string filesDirectory = "uploadFiles")
{
    var directoryPath = Path.Combine(app.Environment.ContentRootPath, filesDirectory);
    Directory.CreateDirectory(directoryPath);
    return Path.Combine(directoryPath, fileName);
}

async Task UploadFileWithName(IFormFile file, string fileSaveName)
{
    var filePath = GetOrCreateFilePath(fileSaveName);
    await using var fileStream = new FileStream(filePath, FileMode.Create);
    await file.CopyToAsync(fileStream);
}

app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    var html = $"""
      <html>
        <body>
          <form action="/upload" method="POST" enctype="multipart/form-data">
            <input name="{token.FormFieldName}" type="hidden" value="{token.RequestToken}"/>
            <input type="file" name="file" placeholder="Upload an image..." accept=".jpg, 
                                                                            .jpeg, .png" />
            <input type="submit" />
          </form> 
        </body>
      </html>
    """;

    return Results.Content(html, "text/html");
});

app.MapPost("/upload", async Task<Results<Ok<string>,
   BadRequest<string>>> (IFormFile file, HttpContext context, IAntiforgery antiforgery) =>
{
    var fileSaveName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
    await UploadFileWithName(file, fileSaveName);
    return TypedResults.Ok("File uploaded successfully!");
});

app.Run();

警告:實作表單時,應用程式必須防止跨網站偽造要求 (XSRF/CSRF) 攻擊。 在上述程式碼中,IAntiforgery 服務可藉由產生和驗證防偽造權杖來防止 XSRF 攻擊:

using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http.HttpResults;

var builder = WebApplication.CreateBuilder();

builder.Services.AddAntiforgery();

var app = builder.Build();
app.UseAntiforgery();

string GetOrCreateFilePath(string fileName, string filesDirectory = "uploadFiles")
{
    var directoryPath = Path.Combine(app.Environment.ContentRootPath, filesDirectory);
    Directory.CreateDirectory(directoryPath);
    return Path.Combine(directoryPath, fileName);
}

async Task UploadFileWithName(IFormFile file, string fileSaveName)
{
    var filePath = GetOrCreateFilePath(fileSaveName);
    await using var fileStream = new FileStream(filePath, FileMode.Create);
    await file.CopyToAsync(fileStream);
}

app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    var html = $"""
      <html>
        <body>
          <form action="/upload" method="POST" enctype="multipart/form-data">
            <input name="{token.FormFieldName}" type="hidden" value="{token.RequestToken}"/>
            <input type="file" name="file" placeholder="Upload an image..." accept=".jpg, 
                                                                            .jpeg, .png" />
            <input type="submit" />
          </form> 
        </body>
      </html>
    """;

    return Results.Content(html, "text/html");
});

app.MapPost("/upload", async Task<Results<Ok<string>,
   BadRequest<string>>> (IFormFile file, HttpContext context, IAntiforgery antiforgery) =>
{
    var fileSaveName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.FileName);
    await UploadFileWithName(file, fileSaveName);
    return TypedResults.Ok("File uploaded successfully!");
});

app.Run();

如需 XSRF 攻擊的詳細資訊,請參閱使用基本 API 的防偽造功能

欲了解更多資訊,請參閱 「最小 API 中的表單綁定」;

IFormFile 集合繫結行為

下表總結了最小 API 中不同 IFormFile 集合參數類型的綁定方式。 路由處理常式中的參數名稱必須與表單欄位名稱相符,這項一般指引適用於 IFormFile 和受支援的具名檔案集合(例如 IReadOnlyList<T>),但不適用於 IFormFileCollection,因為它會繫結所有已上傳的檔案。

參數類型 繫結值 沿用參數名稱嗎?
IFormFileCollection HttpContext.Request.Form.Files 中的所有檔案 No
IFormFile 其表單欄位名稱與參數名稱相符的單一檔案 Yes
IReadOnlyList<IFormFile> 所有表單欄位名稱與參數名稱相符的檔案 Yes
其他 IFormFile 集合類型(IEnumerable<IFormFile>、 List<IFormFile>、、 IFormFile[]等) 不支援 — 參數未被填充 N/A

當你需要所有上傳的檔案,不管表單欄位名稱為何時使用 IFormFileCollection 。 當你只需要表單欄位名稱與參數名稱相符的檔案時,就使用 IReadOnlyList<T> 。

注意事項

前述表格中的 IFormFile 集合繫結規則也適用於 [AsParameters] 類型上的屬性以及表單對應的複合類型,因為表單對應層與 Blazor 共用。

將表單中的資料繫結至集合和複雜型別

支援繫結的項目如下:

  • 集合,例如清單和字典
  • 複雜類型,例如 Todo 或 Project

警告

在 Minimal API 中使用 [FromForm] 的複合型別表單對應不會使用 MVC 模型繫結。 命名空間中的 Microsoft.AspNetCore.Mvc.ModelBinding 屬性,如 [BindNever] 和 [BindRequired],不被支援。 不要用這些屬性來防止過度貼文。 相反地,請使用專用的輸入模型或資料傳輸物件(DTO),只包含用戶端允許修改的屬性。

下列程式碼顯示:

  • 將多部分表單輸入繫結到複雜物件的最小 API 端點。
  • 如何使用防偽服務來支援反偽權杖的產生和驗證。
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAntiforgery();

var app = builder.Build();

app.UseAntiforgery();

app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    var html = $"""
        <html><body>
           <form action="/todo" method="POST" enctype="multipart/form-data">
               <input name="{token.FormFieldName}" 
                                type="hidden" value="{token.RequestToken}" />
               <input type="text" name="name" />
               <input type="date" name="dueDate" />
               <input type="checkbox" name="isCompleted" value="true" />
               <input type="submit" />
               <input name="isCompleted" type="hidden" value="false" /> 
           </form>
        </body></html>
    """;
    return Results.Content(html, "text/html");
});

app.MapPost("/todo", async Task<Results<Ok<Todo>, BadRequest<string>>> 
               ([FromForm] Todo todo, HttpContext context, IAntiforgery antiforgery) =>
{
    try
    {
        await antiforgery.ValidateRequestAsync(context);
        return TypedResults.Ok(todo);
    }
    catch (AntiforgeryValidationException e)
    {
        return TypedResults.BadRequest("Invalid antiforgery token");
    }
});

app.Run();

class Todo
{
    public string Name { get; set; } = string.Empty;
    public bool IsCompleted { get; set; } = false;
    public DateTime DueDate { get; set; } = DateTime.Now.Add(TimeSpan.FromDays(1));
}

在上述程式碼中:

  • 目標參數必須使用 [FromForm] 屬性標註,以區別應從 JSON 主體讀取的參數。
  • 對於使用 Request Delegate 產生器編譯的 Minimal API,不支援從複雜或集合類型的綁定。
  • 標記會顯示額外的隱藏輸入,其名稱為 isCompleted,且值為 false。 如果在提交表單時核取 isCompleted 核取方塊,則 true 和 false 兩個值都會當作值提交。 如果未核取此核取方塊,則只會提交隱藏的輸入值 false。 ASP.NET Core 表單對應程序在繫結至 bool 值時,只會讀取第一個值,因此已核取的核取方塊會得到 true,而未核取的核取方塊會得到 false。

提交至上述端點之表單資料的範例如下所示:

__RequestVerificationToken: CfDJ8Bveip67DklJm5vI2PF2VOUZ594RC8kcGWpTnVV17zCLZi1yrs-CSz426ZRRrQnEJ0gybB0AD7hTU-0EGJXDU-OaJaktgAtWLIaaEWMOWCkoxYYm-9U9eLV7INSUrQ6yBHqdMEE_aJpD4AI72gYiCqc
name: Walk the dog
dueDate: 2024-04-06
isCompleted: true
isCompleted: false

從標頭與查詢字串中繫結陣列和字串值

下列程式碼會示範將查詢字串繫結至簡單型別、字串陣列和 StringValues 的陣列:

// Bind query string values to a primitive type array.
// GET  /tags?q=1&q=2&q=3
app.MapGet("/tags", (int[] q) =>
                      $"tag1: {q[0]} , tag2: {q[1]}, tag3: {q[2]}");

// Bind to a string array.
// GET /tags2?names=john&names=jack&names=jane
app.MapGet("/tags2", (string[] names) =>
            $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}");

// Bind to StringValues.
// GET /tags3?names=john&names=jack&names=jane
app.MapGet("/tags3", (StringValues names) =>
            $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}");

當該型別已實作 TryParse 時,支援將查詢字串或標頭值繫結至複雜型別陣列。 下列程式碼會繫結至字串陣列,並傳回具有指定標記的所有項目:

// GET /todoitems/tags?tags=home&tags=work
app.MapGet("/todoitems/tags", async (Tag[] tags, TodoDb db) =>
{
    return await db.Todos
        .Where(t => tags.Select(i => i.Name).Contains(t.Tag.Name))
        .ToListAsync();
});

下列程式碼會顯示模型和必要的 TryParse 實作:

public class Todo
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsComplete { get; set; }

    // This is an owned entity. 
    public Tag Tag { get; set; } = new();
}

[Owned]
public class Tag
{
    public string? Name { get; set; } = "n/a";

    public static bool TryParse(string? name, out Tag tag)
    {
        if (name is null)
        {
            tag = default!;
            return false;
        }

        tag = new Tag { Name = name };
        return true;
    }
}

下列程式碼會繫結至 int 陣列:

// GET /todoitems/query-string-ids?ids=1&ids=3
app.MapGet("/todoitems/query-string-ids", async (int[] ids, TodoDb db) =>
{
    return await db.Todos
        .Where(t => ids.Contains(t.Id))
        .ToListAsync();
});

若要測試上述程式碼,請新增下列端點以將 Todo 項目填入資料庫:

// POST /todoitems/batch
app.MapPost("/todoitems/batch", async (Todo[] todos, TodoDb db) =>
{
    await db.Todos.AddRangeAsync(todos);
    await db.SaveChangesAsync();

    return Results.Ok(todos);
});

使用 HttpRepl 之類的工具,將下列資料傳遞至先前的端點:

[
    {
        "id": 1,
        "name": "Have Breakfast",
        "isComplete": true,
        "tag": {
            "name": "home"
        }
    },
    {
        "id": 2,
        "name": "Have Lunch",
        "isComplete": true,
        "tag": {
            "name": "work"
        }
    },
    {
        "id": 3,
        "name": "Have Supper",
        "isComplete": true,
        "tag": {
            "name": "home"
        }
    },
    {
        "id": 4,
        "name": "Have Snacks",
        "isComplete": true,
        "tag": {
            "name": "N/A"
        }
    }
]

下列程式碼會繫結至標頭索引鍵 X-Todo-Id,並傳回具有相符 Todo 值的 Id 項目:

// GET /todoitems/header-ids
// The keys of the headers should all be X-Todo-Id with different values
app.MapGet("/todoitems/header-ids", async ([FromHeader(Name = "X-Todo-Id")] int[] ids, TodoDb db) =>
{
    return await db.Todos
        .Where(t => ids.Contains(t.Id))
        .ToListAsync();
});

注意事項

當從查詢字串綁定不可為 null 的 string[] 時,若缺少相符的查詢字串值,則會產生空陣列而非 null。 若參數被宣告為可空(例如 string[]?),或預設值為 null(例如 [FromQuery] string[]? names = null),省略查詢參數會得到 null。

具有 [AsParameters] 引數清單的參數繫結

AsParametersAttribute 可實現型別的簡單參數繫結,而不是複雜或遞迴模型繫結。

請考慮下列程式碼:

using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.Select(x => new TodoItemDTO(x)).ToListAsync());

app.MapGet("/todoitems/{id}",
                             async (int Id, TodoDb Db) =>
    await Db.Todos.FindAsync(Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());
// Remaining code removed for brevity.

考慮下列 GET 端點:

app.MapGet("/todoitems/{id}",
                             async (int Id, TodoDb Db) =>
    await Db.Todos.FindAsync(Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());

下列 struct 可用來取代上述強調顯示的參數:

struct TodoItemRequest
{
    public int Id { get; set; }
    public TodoDb Db { get; set; }
}

重構後的 GET 端點使用前述的 struct,並搭配 AsParameters 屬性:

app.MapGet("/ap/todoitems/{id}",
                                async ([AsParameters] TodoItemRequest request) =>
    await request.Db.Todos.FindAsync(request.Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());

下列程式碼會顯示應用程式中的其他端點:

app.MapPost("/todoitems", async (TodoItemDTO Dto, TodoDb Db) =>
{
    var todoItem = new Todo
    {
        IsComplete = Dto.IsComplete,
        Name = Dto.Name
    };

    Db.Todos.Add(todoItem);
    await Db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todoItem.Id}", new TodoItemDTO(todoItem));
});

app.MapPut("/todoitems/{id}", async (int Id, TodoItemDTO Dto, TodoDb Db) =>
{
    var todo = await Db.Todos.FindAsync(Id);

    if (todo is null) return Results.NotFound();

    todo.Name = Dto.Name;
    todo.IsComplete = Dto.IsComplete;

    await Db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/todoitems/{id}", async (int Id, TodoDb Db) =>
{
    if (await Db.Todos.FindAsync(Id) is Todo todo)
    {
        Db.Todos.Remove(todo);
        await Db.SaveChangesAsync();
        return Results.Ok(new TodoItemDTO(todo));
    }

    return Results.NotFound();
});

下列類別可用來重構參數清單:

class CreateTodoItemRequest
{
    public TodoItemDTO Dto { get; set; } = default!;
    public TodoDb Db { get; set; } = default!;
}

class EditTodoItemRequest
{
    public int Id { get; set; }
    public TodoItemDTO Dto { get; set; } = default!;
    public TodoDb Db { get; set; } = default!;
}

下列程式碼會顯示使用 AsParameters 和上述 struct 與類別的重構端點:

app.MapPost("/ap/todoitems", async ([AsParameters] CreateTodoItemRequest request) =>
{
    var todoItem = new Todo
    {
        IsComplete = request.Dto.IsComplete,
        Name = request.Dto.Name
    };

    request.Db.Todos.Add(todoItem);
    await request.Db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todoItem.Id}", new TodoItemDTO(todoItem));
});

app.MapPut("/ap/todoitems/{id}", async ([AsParameters] EditTodoItemRequest request) =>
{
    var todo = await request.Db.Todos.FindAsync(request.Id);

    if (todo is null) return Results.NotFound();

    todo.Name = request.Dto.Name;
    todo.IsComplete = request.Dto.IsComplete;

    await request.Db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/ap/todoitems/{id}", async ([AsParameters] TodoItemRequest request) =>
{
    if (await request.Db.Todos.FindAsync(request.Id) is Todo todo)
    {
        request.Db.Todos.Remove(todo);
        await request.Db.SaveChangesAsync();
        return Results.Ok(new TodoItemDTO(todo));
    }

    return Results.NotFound();
});

下列 record 型別可用來取代上述參數:

record TodoItemRequest(int Id, TodoDb Db);
record CreateTodoItemRequest(TodoItemDTO Dto, TodoDb Db);
record EditTodoItemRequest(int Id, TodoItemDTO Dto, TodoDb Db);

使用 struct 搭配 AsParameters 比使用 record 型別更有效果。

AspNetCore.Docs.Samples 存放庫中的完整範例程式碼。

自訂繫結

自訂參數繫結有三種方式:

  1. 對於路由、查詢和標頭繫結來源,可藉由為該型別新增靜態 TryParse 方法來繫結自訂型別。
  2. 藉由在型別上實作 BindAsync 方法來控制繫結程序。
  3. 針對進階案例,實作IBindableFromHttpContext<TSelf>介面,以從HttpContext直接提供自訂的繫結邏輯。

嘗試解析 (TryParse)

TryParse 有兩個 API:

public static bool TryParse(string value, out T result);
public static bool TryParse(string value, IFormatProvider provider, out T result);

下列程式碼會使用 URI Point: 12.3, 10.1 顯示 /map?Point=12.3,10.1:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// GET /map?Point=12.3,10.1
app.MapGet("/map", (Point point) => $"Point: {point.X}, {point.Y}");

app.Run();

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }

    public static bool TryParse(string? value, IFormatProvider? provider,
                                out Point? point)
    {
        // Format is "(12.3,10.1)"
        var trimmedValue = value?.TrimStart('(').TrimEnd(')');
        var segments = trimmedValue?.Split(',',
                StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        if (segments?.Length == 2
            && double.TryParse(segments[0], out var x)
            && double.TryParse(segments[1], out var y))
        {
            point = new Point { X = x, Y = y };
            return true;
        }

        point = null;
        return false;
    }
}

BindAsync

BindAsync 有下列 API:

public static ValueTask<T?> BindAsync(HttpContext context, ParameterInfo parameter);
public static ValueTask<T?> BindAsync(HttpContext context);

下列程式碼會使用 URI SortBy:xyz, SortDirection:Desc, CurrentPage:99 顯示 /products?SortBy=xyz&SortDir=Desc&Page=99:

using System.Reflection;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// GET /products?SortBy=xyz&SortDir=Desc&Page=99
app.MapGet("/products", (PagingData pageData) => $"SortBy:{pageData.SortBy}, " +
       $"SortDirection:{pageData.SortDirection}, CurrentPage:{pageData.CurrentPage}");

app.Run();

public class PagingData
{
    public string? SortBy { get; init; }
    public SortDirection SortDirection { get; init; }
    public int CurrentPage { get; init; } = 1;

    public static ValueTask<PagingData?> BindAsync(HttpContext context,
                                                   ParameterInfo parameter)
    {
        const string sortByKey = "sortBy";
        const string sortDirectionKey = "sortDir";
        const string currentPageKey = "page";

        Enum.TryParse<SortDirection>(context.Request.Query[sortDirectionKey],
                                     ignoreCase: true, out var sortDirection);
        int.TryParse(context.Request.Query[currentPageKey], out var page);
        page = page == 0 ? 1 : page;

        var result = new PagingData
        {
            SortBy = context.Request.Query[sortByKey],
            SortDirection = sortDirection,
            CurrentPage = page
        };

        return ValueTask.FromResult<PagingData?>(result);
    }
}

public enum SortDirection
{
    Default,
    Asc,
    Desc
}

自訂參數繫結與 IBindableFromHttpContext

ASP.NET Core 提供在使用 IBindableFromHttpContext<TSelf> 介面的最小 API 中支援自訂參數繫結。 此介面是使用 C# 11 的靜態抽象成員引進的,可讓您建立可直接在路由處理常式參數中從 HTTP 內容系結的類型。

public interface IBindableFromHttpContext<TSelf>
    where TSelf : class, IBindableFromHttpContext<TSelf>
{
    static abstract ValueTask<TSelf?> BindAsync(HttpContext context, ParameterInfo parameter);
}

透過實作 IBindableFromHttpContext<TSelf>,您可以建立自訂類型,這些類型能夠從 HttpContext 中處理自己的繫結邏輯。 當路由處理常式包含此類型的參數時,架構會自動呼叫靜態 BindAsync 方法來建立實例:

using CustomBindingExample;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();

app.MapGet("/", () => "Hello, IBindableFromHttpContext example!");

app.MapGet("/custom-binding", (CustomBoundParameter param) =>
{
    return $"Value from custom binding: {param.Value}";
});

app.MapGet("/combined/{id}", (int id, CustomBoundParameter param) =>
{
    return $"ID: {id}, Custom Value: {param.Value}";
});

以下是從 HTTP 標頭繫結的自訂參數實作範例:

using System.Reflection;

namespace CustomBindingExample;

public class CustomBoundParameter : IBindableFromHttpContext<CustomBoundParameter>
{
    public string Value { get; init; } = default!;

    public static ValueTask<CustomBoundParameter?> BindAsync(HttpContext context, ParameterInfo parameter)
    {
        // Custom binding logic here
        // This example reads from a custom header
        var value = context.Request.Headers["X-Custom-Header"].ToString();
        
        // If no header was provided, you could fall back to a query parameter
        if (string.IsNullOrEmpty(value))
        {
            value = context.Request.Query["customValue"].ToString();
        }
        
        return ValueTask.FromResult<CustomBoundParameter?>(new CustomBoundParameter 
        {
            Value = value
        });
    }
}

您也可以在自訂繫結邏輯中實作驗證:

app.MapGet("/validated", (ValidatedParameter param) =>
{
    if (string.IsNullOrEmpty(param.Value))
    {
        return Results.BadRequest("Value cannot be empty");
    }
    
    return Results.Ok($"Validated value: {param.Value}");
});

檢視或下載範例程式碼 (如何下載)

繫結失敗

繫結失敗時,架構會記錄偵錯訊息,並根據失敗模式將各種狀態碼傳回至用戶端。

失敗模式 可為空值的參數型別 繫結來源 狀態碼
{ParameterType}.TryParse 傳回 false 是 路由/查詢/標頭 400
{ParameterType}.BindAsync 傳回 null 是 習慣 400
{ParameterType}.BindAsync 拋出 不重要 習慣 500
無法還原 JSON 主體 不重要 內文 400
錯誤的內容類型 (非 application/json) 不重要 內文 415

當 ThrowOnBadRequest 是 false時,擁有過濾管線的端點會在參數檢查失敗(如路由、查詢、標頭解析失敗,或缺少必要參數)後執行過濾器,允許過濾器觀察 400 狀態碼並替換回應主體。 端點過濾器不會為讀取正文失敗(例如格式錯誤的 JSON 或不支援的內容類型)或綁定例外執行。 欲了解更多資訊,請參閱「篩選器與參數綁定失敗」。

繫結優先順序

從參數判斷繫結來源的規則:

  1. 如下順序在參數上定義的明確屬性 (From* 屬性):
    1. 路由值:[FromRoute]
    2. 查詢字串:[FromQuery]
    3. 標題:[FromHeader]
    4. 本文:[FromBody]
    5. 表單:[FromForm]
    6. 服務:[FromServices]
    7. 參數值:[AsParameters]
  2. 特殊型別
    1. HttpContext
    2. HttpRequest (HttpContext.Request)
    3. HttpResponse (HttpContext.Response)
    4. ClaimsPrincipal (HttpContext.User)
    5. CancellationToken (HttpContext.RequestAborted)
    6. IFormCollection (HttpContext.Request.Form)
    7. IFormFileCollection (HttpContext.Request.Form.Files)
    8. IFormFile (HttpContext.Request.Form.Files[paramName])
    9. Stream (HttpContext.Request.Body)
    10. PipeReader (HttpContext.Request.BodyReader)
  3. 參數型別具有有效的靜態 BindAsync 方法。
  4. 參數型別是字串或具有有效的靜態 TryParse 方法。
    1. 如果參數名稱存在於路由範本中 (例如 app.Map("/todo/{id}", (int id) => {});),則會從路由繫結。
    2. 繫結自查詢字串。
  5. 如果參數型別是相依性插入所提供的服務,它會使用該服務作為來源。
  6. 參數來自本文。

設定用於主體繫結的 JSON 反序列化選項

主體繫結來源會使用 System.Text.Json 來進行反序列化。 無法變更此預設值,但可以設定 JSON 序列化和還原序列化選項。

全域設定 JSON 還原序列化選項

您可以叫用 ConfigureHttpJsonOptions 來設定要全域套用至應用程式的選項。 下列範例包含公開欄位,並將 JSON 輸出格式化。

var builder = WebApplication.CreateBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options => {
    options.SerializerOptions.WriteIndented = true;
    options.SerializerOptions.IncludeFields = true;
});

var app = builder.Build();

app.MapPost("/", (Todo todo) => {
    if (todo is not null) {
        todo.Name = todo.NameField;
    }
    return todo;
});

app.Run();

class Todo {
    public string? Name { get; set; }
    public string? NameField;
    public bool IsComplete { get; set; }
}
// If the request body contains the following JSON:
//
// {"nameField":"Walk dog", "isComplete":false}
//
// The endpoint returns the following JSON:
//
// {
//    "name":"Walk dog",
//    "nameField":"Walk dog",
//    "isComplete":false
// }

由於範例程式碼會同時設定序列化和還原序列化,因此其可以讀取 NameField 並將 NameField 包含在輸出的 JSON 中。

設定端點的 JSON 還原序列化選項

ReadFromJsonAsync 具有會接受 JsonSerializerOptions 物件的多載。 下列範例包含公開欄位,並將 JSON 輸出格式化。

using System.Text.Json;

var app = WebApplication.Create();

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) { 
    IncludeFields = true, 
    WriteIndented = true
};

app.MapPost("/", async (HttpContext context) => {
    if (context.Request.HasJsonContentType()) {
        var todo = await context.Request.ReadFromJsonAsync<Todo>(options);
        if (todo is not null) {
            todo.Name = todo.NameField;
        }
        return Results.Ok(todo);
    }
    else {
        return Results.BadRequest();
    }
});

app.Run();

class Todo
{
    public string? Name { get; set; }
    public string? NameField;
    public bool IsComplete { get; set; }
}
// If the request body contains the following JSON:
//
// {"nameField":"Walk dog", "isComplete":false}
//
// The endpoint returns the following JSON:
//
// {
//    "name":"Walk dog",
//    "isComplete":false
// }

由於上述程式碼僅會將自訂選項套用至還原序列化,因此輸出 JSON 會排除 NameField。

讀取請求本文

直接使用 HttpContext 或 HttpRequest 參數讀取要求主體:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/uploadstream", async (IConfiguration config, HttpRequest request) =>
{
    var filePath = Path.Combine(config["StoredFilesPath"], Path.GetRandomFileName());

    await using var writeStream = File.Create(filePath);
    await request.BodyReader.CopyToAsync(writeStream);
});

app.Run();

上述 程式碼:

參數繫結是將請求資料轉換為路由處理常式所定義的強型別參數的過程。 繫結來源會決定參數的繫結來源位置。 繫結來源可以是明確或根據 HTTP 方法和參數型別推斷。

支援的繫結來源:

  • 路由值
  • 查詢字串
  • 頁首
  • 主體(JSON 格式)
  • 由依賴注入提供的服務
  • 自訂

.NET 6 和 7 原生不支援從表單值進行繫結。

下列 GET 路由處理常式會使用以下其中一些參數繫結來源:

var builder = WebApplication.CreateBuilder(args);

// Added as service
builder.Services.AddSingleton<Service>();

var app = builder.Build();

app.MapGet("/{id}", (int id,
                     int page,
                     [FromHeader(Name = "X-CUSTOM-HEADER")] string customHeader,
                     Service service) => { });

class Service { }

下表顯示上述範例中所使用參數與關聯繫結來源之間的關聯性。

參數 繫結來源
id 路由值
page 查詢字串
customHeader 標頭
service 由相依性注入提供

例如,給定以下 HTTP 請求:

GET /42?page=3 HTTP/1.1
Host: example.com
X-CUSTOM-HEADER: hello
  • 42 在 /42 中符合路由範本 {id} 的 /{id},並繫結至 id 路由參數。
  • page=3 在 ?page=3 中匹配查詢字串鍵 page,並綁定至 page 參數。
  • X-CUSTOM-HEADER: hello 匹配 [FromHeader(Name = "X-CUSTOM-HEADER")] 標頭屬性並綁定到 customHeader。
  • service 是從相依注入(DI)容器中解析,而非從接收的 HTTP 請求中解析。

HTTP 方法 GET、HEAD、OPTIONS 和 DELETE 不會隱含從本文繫結。 若要從本文 (JSON 格式) 繫結這些 HTTP 方法,請明確繫結[FromBody] 或從 HttpRequest 讀取。

下列範例 POST 路由處理常式會針對 person 參數使用本文 (JSON 格式) 的繫結來源:

var builder = WebApplication.CreateBuilder(args);

var app = builder.Build();

app.MapPost("/", (Person person) => { });

record Person(string Name, int Age);

上述範例中的參數全都會自動從要求資料繫結。 為了示範參數繫結所提供的便利性,下列路由處理常式將示範如何直接從要求讀取要求資料:

app.MapGet("/{id}", (HttpRequest request) =>
{
    var id = request.RouteValues["id"];
    var page = request.Query["page"];
    var customHeader = request.Headers["X-CUSTOM-HEADER"];

    // ...
});

app.MapPost("/", async (HttpRequest request) =>
{
    var person = await request.ReadFromJsonAsync<Person>();

    // ...
});

明確參數繫結

屬性可用來明確宣告參數繫結的來源位置。

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

// Added as service
builder.Services.AddSingleton<Service>();

var app = builder.Build();


app.MapGet("/{id}", ([FromRoute] int id,
                     [FromQuery(Name = "p")] int page,
                     [FromServices] Service service,
                     [FromHeader(Name = "Content-Type")] string contentType) 
                     => {});

class Service { }

record Person(string Name, int Age);
參數 繫結來源
id 名稱為 id 的路由值
page 具有名稱 "p" 的查詢字串
service 由相依性注入提供
contentType 具有名稱 "Content-Type" 的標頭

注意事項

.NET 6 和 7 原生不支援從表單值進行繫結。

使用相依性注入的參數繫結

當類型被設定為服務時,最小 API 的參數會透過 依賴注入 進行綁定。 不需要將 [FromServices] 屬性明確套用至參數。 在下列程式碼中,這兩個動作都會傳回時間:

using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IDateTime, SystemDateTime>();

var app = builder.Build();

app.MapGet("/",   (               IDateTime dateTime) => dateTime.Now);
app.MapGet("/fs", ([FromServices] IDateTime dateTime) => dateTime.Now);
app.Run();

選擇性參數

在路由處理程式中宣告的參數會被視為必要:

  • 如果要求符合路由,則只有在要求中提供所有必要的參數時,路由處理常式才會執行。
  • 無法提供所有必要參數會導致錯誤。
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int pageNumber) => $"Requesting page {pageNumber}");

app.Run();
URI 結果
/products?pageNumber=3 3 項已傳回
/products BadHttpRequestException:查詢字串未提供必要的參數 "int pageNumber"。
/products/1 HTTP 404 錯誤,沒有相符的路由

若要將 pageNumber 設為選用,請將型別定義為選用或提供預設值:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int? pageNumber) => $"Requesting page {pageNumber ?? 1}");

string ListProducts(int pageNumber = 1) => $"Requesting page {pageNumber}";

app.MapGet("/products2", ListProducts);

app.Run();
URI 結果
/products?pageNumber=3 3 項已傳回
/products 已傳回 1 項
/products2 已傳回 1 項

前述的可為 Null 設定與預設值適用於所有來源:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/products", (Product? product) => { });

app.Run();

如果未傳送任何要求主體,上述程式碼會以 null 的 product 呼叫該方法。

注意:如果提供無效資料且參數可為 Null,則路由處理常式不會執行。

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products", (int? pageNumber) => $"Requesting page {pageNumber ?? 1}");

app.Run();
URI 結果
/products?pageNumber=3 3 傳回
/products 1 傳回
/products?pageNumber=two BadHttpRequestException:無法從 "two" 繫結參數 "Nullable<int> pageNumber"。
/products/two HTTP 404 錯誤,沒有相符的路由

如需詳細資訊,請參閱繫結失敗一節。

特殊型別

下列型別會在沒有明確屬性的情況下繫結:

  • HttpContext:保存有關目前 HTTP 請求或回應之所有資訊的內容物件:

    app.MapGet("/", (HttpContext context) => context.Response.WriteAsync("Hello World"));
    
  • HttpRequest 和 HttpResponse:HTTP 要求和 HTTP 回應:

    app.MapGet("/", (HttpRequest request, HttpResponse response) =>
        response.WriteAsync($"Hello World {request.Query["name"]}"));
    
  • CancellationToken:與目前 HTTP 要求相關聯的取消權杖:

    app.MapGet("/", async (CancellationToken cancellationToken) => 
        await MakeLongRunningRequestAsync(cancellationToken));
    
  • ClaimsPrincipal:與要求相關聯的使用者,繫結自 HttpContext.User:

    app.MapGet("/", (ClaimsPrincipal user) => user.Identity.Name);
    

將請求本文繫結為 Stream 或 PipeReader

要求主體可繫結為 Stream 或 PipeReader,以有效支援使用者必須處理資料的情境,並:

  • 將資料儲存至 Blob 儲存體,或將資料排入佇列提供者的佇列。
  • 使用工作處理序或雲端函式來處理已儲存的資料。

例如,資料可能會加入佇列至 Azure 佇列儲存體,或儲存在 Azure Blob 儲存體中。

下列程式碼會實作背景佇列:

using System.Text.Json;
using System.Threading.Channels;

namespace BackgroundQueueService;

class BackgroundQueue : BackgroundService
{
    private readonly Channel<ReadOnlyMemory<byte>> _queue;
    private readonly ILogger<BackgroundQueue> _logger;

    public BackgroundQueue(Channel<ReadOnlyMemory<byte>> queue,
                               ILogger<BackgroundQueue> logger)
    {
        _queue = queue;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await foreach (var dataStream in _queue.Reader.ReadAllAsync(stoppingToken))
        {
            try
            {
                var person = JsonSerializer.Deserialize<Person>(dataStream.Span)!;
                _logger.LogInformation($"{person.Name} is {person.Age} " +
                                       $"years and from {person.Country}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }
        }
    }
}

class Person
{
    public string Name { get; set; } = String.Empty;
    public int Age { get; set; }
    public string Country { get; set; } = String.Empty;
}

下列程式碼會將要求主體繫結到 Stream:

app.MapPost("/register", async (HttpRequest req, Stream body,
                                 Channel<ReadOnlyMemory<byte>> queue) =>
{
    if (req.ContentLength is not null && req.ContentLength > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // We're not above the message size and we have a content length, or
    // we're a chunked request and we're going to read up to the maxMessageSize + 1. 
    // We add one to the message size so that we can detect when a chunked request body
    // is bigger than our configured max.
    var readSize = (int?)req.ContentLength ?? (maxMessageSize + 1);

    var buffer = new byte[readSize];

    // Read at least that many bytes from the body.
    var read = await body.ReadAtLeastAsync(buffer, readSize, throwOnEndOfStream: false);

    // We read more than the max, so this is a bad request.
    if (read > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // Attempt to send the buffer to the background queue.
    if (queue.Writer.TryWrite(buffer.AsMemory(0..read)))
    {
        return Results.Accepted();
    }

    // We couldn't accept the message since we're overloaded.
    return Results.StatusCode(StatusCodes.Status429TooManyRequests);
});

下列程式碼會顯示完整的 Program.cs 檔案:

using System.Threading.Channels;
using BackgroundQueueService;

var builder = WebApplication.CreateBuilder(args);
// The max memory to use for the upload endpoint on this instance.
var maxMemory = 500 * 1024 * 1024;

// The max size of a single message, staying below the default LOH size of 85K.
var maxMessageSize = 80 * 1024;

// The max size of the queue based on those restrictions
var maxQueueSize = maxMemory / maxMessageSize;

// Create a channel to send data to the background queue.
builder.Services.AddSingleton<Channel<ReadOnlyMemory<byte>>>((_) =>
                     Channel.CreateBounded<ReadOnlyMemory<byte>>(maxQueueSize));

// Create a background queue service.
builder.Services.AddHostedService<BackgroundQueue>();
var app = builder.Build();

// curl --request POST 'https://localhost:<port>/register' --header 'Content-Type: application/json' --data-raw '{ "Name":"Samson", "Age": 23, "Country":"Nigeria" }'
// curl --request POST "https://localhost:<port>/register" --header "Content-Type: application/json" --data-raw "{ \"Name\":\"Samson\", \"Age\": 23, \"Country\":\"Nigeria\" }"
app.MapPost("/register", async (HttpRequest req, Stream body,
                                 Channel<ReadOnlyMemory<byte>> queue) =>
{
    if (req.ContentLength is not null && req.ContentLength > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // We're not above the message size and we have a content length, or
    // we're a chunked request and we're going to read up to the maxMessageSize + 1. 
    // We add one to the message size so that we can detect when a chunked request body
    // is bigger than our configured max.
    var readSize = (int?)req.ContentLength ?? (maxMessageSize + 1);

    var buffer = new byte[readSize];

    // Read at least that many bytes from the body.
    var read = await body.ReadAtLeastAsync(buffer, readSize, throwOnEndOfStream: false);

    // We read more than the max, so this is a bad request.
    if (read > maxMessageSize)
    {
        return Results.BadRequest();
    }

    // Attempt to send the buffer to the background queue.
    if (queue.Writer.TryWrite(buffer.AsMemory(0..read)))
    {
        return Results.Accepted();
    }

    // We couldn't accept the message since we're overloaded.
    return Results.StatusCode(StatusCodes.Status429TooManyRequests);
});

app.Run();
  • 讀取資料時,Stream 和 HttpRequest.Body 是相同的物件。
  • 要求主體預設不會被緩衝。 讀取本文之後,將無法倒轉。 無法重複讀取資料流。
  • Stream 和 PipeReader 無法在基本動作處理常式之外使用,因為基礎緩衝區將會受到處置或重複使用。

使用 IFormFile 和 IFormFileCollection 上傳檔案

下列程式碼會使用 IFormFile 和 IFormFileCollection 來上傳檔案:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.MapPost("/upload", async (IFormFile file) =>
{
    var tempFile = Path.GetTempFileName();
    app.Logger.LogInformation(tempFile);
    using var stream = File.OpenWrite(tempFile);
    await file.CopyToAsync(stream);
});

app.MapPost("/upload_many", async (IFormFileCollection myFiles) =>
{
    foreach (var file in myFiles)
    {
        var tempFile = Path.GetTempFileName();
        app.Logger.LogInformation(tempFile);
        using var stream = File.OpenWrite(tempFile);
        await file.CopyToAsync(stream);
    }
});

app.Run();

支援使用授權標頭、用戶端憑證或 cookie 標頭的已驗證檔案上傳要求。

.NET 7 中的 ASP.NET Core 沒有內建的防偽造支援。 Antiforgery 可在 .NET 8 或更新版本中的 ASP.NET Core 中使用。 不過,可以使用 IAntiforgery 服務來實作此功能。

從標頭與查詢字串中繫結陣列和字串值

下列程式碼會示範將查詢字串繫結至簡單型別、字串陣列和 StringValues 的陣列:

// Bind query string values to a primitive type array.
// GET  /tags?q=1&q=2&q=3
app.MapGet("/tags", (int[] q) =>
                      $"tag1: {q[0]} , tag2: {q[1]}, tag3: {q[2]}");

// Bind to a string array.
// GET /tags2?names=john&names=jack&names=jane
app.MapGet("/tags2", (string[] names) =>
            $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}");

// Bind to StringValues.
// GET /tags3?names=john&names=jack&names=jane
app.MapGet("/tags3", (StringValues names) =>
            $"tag1: {names[0]} , tag2: {names[1]}, tag3: {names[2]}");

當該型別已實作 TryParse 時,支援將查詢字串或標頭值繫結至複雜型別陣列。 下列程式碼會繫結至字串陣列,並傳回具有指定標記的所有項目:

// GET /todoitems/tags?tags=home&tags=work
app.MapGet("/todoitems/tags", async (Tag[] tags, TodoDb db) =>
{
    return await db.Todos
        .Where(t => tags.Select(i => i.Name).Contains(t.Tag.Name))
        .ToListAsync();
});

下列程式碼會顯示模型和必要的 TryParse 實作:

public class Todo
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public bool IsComplete { get; set; }

    // This is an owned entity. 
    public Tag Tag { get; set; } = new();
}

[Owned]
public class Tag
{
    public string? Name { get; set; } = "n/a";

    public static bool TryParse(string? name, out Tag tag)
    {
        if (name is null)
        {
            tag = default!;
            return false;
        }

        tag = new Tag { Name = name };
        return true;
    }
}

下列程式碼會繫結至 int 陣列:

// GET /todoitems/query-string-ids?ids=1&ids=3
app.MapGet("/todoitems/query-string-ids", async (int[] ids, TodoDb db) =>
{
    return await db.Todos
        .Where(t => ids.Contains(t.Id))
        .ToListAsync();
});

若要測試上述程式碼,請新增下列端點以將 Todo 項目填入資料庫:

// POST /todoitems/batch
app.MapPost("/todoitems/batch", async (Todo[] todos, TodoDb db) =>
{
    await db.Todos.AddRangeAsync(todos);
    await db.SaveChangesAsync();

    return Results.Ok(todos);
});

使用 HttpRepl 之類的 API 測試工具,將下列資料傳遞至先前的端點:

[
    {
        "id": 1,
        "name": "Have Breakfast",
        "isComplete": true,
        "tag": {
            "name": "home"
        }
    },
    {
        "id": 2,
        "name": "Have Lunch",
        "isComplete": true,
        "tag": {
            "name": "work"
        }
    },
    {
        "id": 3,
        "name": "Have Supper",
        "isComplete": true,
        "tag": {
            "name": "home"
        }
    },
    {
        "id": 4,
        "name": "Have Snacks",
        "isComplete": true,
        "tag": {
            "name": "N/A"
        }
    }
]

下列程式碼會繫結至標頭索引鍵 X-Todo-Id,並傳回具有相符 Todo 值的 Id 項目:

// GET /todoitems/header-ids
// The keys of the headers should all be X-Todo-Id with different values
app.MapGet("/todoitems/header-ids", async ([FromHeader(Name = "X-Todo-Id")] int[] ids, TodoDb db) =>
{
    return await db.Todos
        .Where(t => ids.Contains(t.Id))
        .ToListAsync();
});

注意事項

當從查詢字串綁定不可為 null 的 string[] 時,若缺少相符的查詢字串值,則會產生空陣列而非 null。 若參數被宣告為可空(例如 string[]?),或預設值為 null(例如 [FromQuery] string[]? names = null),省略查詢參數會得到 null。

具有 [AsParameters] 引數清單的參數繫結

AsParametersAttribute 可實現型別的簡單參數繫結,而不是複雜或遞迴模型繫結。

請考慮下列程式碼:

using Microsoft.EntityFrameworkCore;
using TodoApi.Models;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("TodoList"));
var app = builder.Build();

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.Select(x => new TodoItemDTO(x)).ToListAsync());

app.MapGet("/todoitems/{id}",
                             async (int Id, TodoDb Db) =>
    await Db.Todos.FindAsync(Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());
// Remaining code removed for brevity.

考慮下列 GET 端點:

app.MapGet("/todoitems/{id}",
                             async (int Id, TodoDb Db) =>
    await Db.Todos.FindAsync(Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());

下列 struct 可用來取代上述強調顯示的參數:

struct TodoItemRequest
{
    public int Id { get; set; }
    public TodoDb Db { get; set; }
}

重構後的 GET 端點使用前述的 struct,並搭配 AsParameters 屬性:

app.MapGet("/ap/todoitems/{id}",
                                async ([AsParameters] TodoItemRequest request) =>
    await request.Db.Todos.FindAsync(request.Id)
        is Todo todo
            ? Results.Ok(new TodoItemDTO(todo))
            : Results.NotFound());

下列程式碼會顯示應用程式中的其他端點:

app.MapPost("/todoitems", async (TodoItemDTO Dto, TodoDb Db) =>
{
    var todoItem = new Todo
    {
        IsComplete = Dto.IsComplete,
        Name = Dto.Name
    };

    Db.Todos.Add(todoItem);
    await Db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todoItem.Id}", new TodoItemDTO(todoItem));
});

app.MapPut("/todoitems/{id}", async (int Id, TodoItemDTO Dto, TodoDb Db) =>
{
    var todo = await Db.Todos.FindAsync(Id);

    if (todo is null) return Results.NotFound();

    todo.Name = Dto.Name;
    todo.IsComplete = Dto.IsComplete;

    await Db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/todoitems/{id}", async (int Id, TodoDb Db) =>
{
    if (await Db.Todos.FindAsync(Id) is Todo todo)
    {
        Db.Todos.Remove(todo);
        await Db.SaveChangesAsync();
        return Results.Ok(new TodoItemDTO(todo));
    }

    return Results.NotFound();
});

下列類別可用來重構參數清單:

class CreateTodoItemRequest
{
    public TodoItemDTO Dto { get; set; } = default!;
    public TodoDb Db { get; set; } = default!;
}

class EditTodoItemRequest
{
    public int Id { get; set; }
    public TodoItemDTO Dto { get; set; } = default!;
    public TodoDb Db { get; set; } = default!;
}

下列程式碼會顯示使用 AsParameters 和上述 struct 與類別的重構端點:

app.MapPost("/ap/todoitems", async ([AsParameters] CreateTodoItemRequest request) =>
{
    var todoItem = new Todo
    {
        IsComplete = request.Dto.IsComplete,
        Name = request.Dto.Name
    };

    request.Db.Todos.Add(todoItem);
    await request.Db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todoItem.Id}", new TodoItemDTO(todoItem));
});

app.MapPut("/ap/todoitems/{id}", async ([AsParameters] EditTodoItemRequest request) =>
{
    var todo = await request.Db.Todos.FindAsync(request.Id);

    if (todo is null) return Results.NotFound();

    todo.Name = request.Dto.Name;
    todo.IsComplete = request.Dto.IsComplete;

    await request.Db.SaveChangesAsync();

    return Results.NoContent();
});

app.MapDelete("/ap/todoitems/{id}", async ([AsParameters] TodoItemRequest request) =>
{
    if (await request.Db.Todos.FindAsync(request.Id) is Todo todo)
    {
        request.Db.Todos.Remove(todo);
        await request.Db.SaveChangesAsync();
        return Results.Ok(new TodoItemDTO(todo));
    }

    return Results.NotFound();
});

下列 record 型別可用來取代上述參數:

record TodoItemRequest(int Id, TodoDb Db);
record CreateTodoItemRequest(TodoItemDTO Dto, TodoDb Db);
record EditTodoItemRequest(int Id, TodoItemDTO Dto, TodoDb Db);

使用 struct 搭配 AsParameters 比使用 record 型別更有效果。

AspNetCore.Docs.Samples 存放庫中的完整範例程式碼。

自訂繫結

自訂參數繫結有三種方式:

  1. 對於路由、查詢和標頭繫結來源,可藉由為該型別新增靜態 TryParse 方法來繫結自訂型別。
  2. 藉由在型別上實作 BindAsync 方法來控制繫結程序。
  3. 針對進階案例,實作IBindableFromHttpContext<TSelf>介面,以從HttpContext直接提供自訂的繫結邏輯。

嘗試解析 (TryParse)

TryParse 有兩個 API:

public static bool TryParse(string value, out T result);
public static bool TryParse(string value, IFormatProvider provider, out T result);

下列程式碼會使用 URI Point: 12.3, 10.1 顯示 /map?Point=12.3,10.1:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// GET /map?Point=12.3,10.1
app.MapGet("/map", (Point point) => $"Point: {point.X}, {point.Y}");

app.Run();

public class Point
{
    public double X { get; set; }
    public double Y { get; set; }

    public static bool TryParse(string? value, IFormatProvider? provider,
                                out Point? point)
    {
        // Format is "(12.3,10.1)"
        var trimmedValue = value?.TrimStart('(').TrimEnd(')');
        var segments = trimmedValue?.Split(',',
                StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
        if (segments?.Length == 2
            && double.TryParse(segments[0], out var x)
            && double.TryParse(segments[1], out var y))
        {
            point = new Point { X = x, Y = y };
            return true;
        }

        point = null;
        return false;
    }
}

BindAsync

BindAsync 有下列 API:

public static ValueTask<T?> BindAsync(HttpContext context, ParameterInfo parameter);
public static ValueTask<T?> BindAsync(HttpContext context);

下列程式碼會使用 URI SortBy:xyz, SortDirection:Desc, CurrentPage:99 顯示 /products?SortBy=xyz&SortDir=Desc&Page=99:

using System.Reflection;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// GET /products?SortBy=xyz&SortDir=Desc&Page=99
app.MapGet("/products", (PagingData pageData) => $"SortBy:{pageData.SortBy}, " +
       $"SortDirection:{pageData.SortDirection}, CurrentPage:{pageData.CurrentPage}");

app.Run();

public class PagingData
{
    public string? SortBy { get; init; }
    public SortDirection SortDirection { get; init; }
    public int CurrentPage { get; init; } = 1;

    public static ValueTask<PagingData?> BindAsync(HttpContext context,
                                                   ParameterInfo parameter)
    {
        const string sortByKey = "sortBy";
        const string sortDirectionKey = "sortDir";
        const string currentPageKey = "page";

        Enum.TryParse<SortDirection>(context.Request.Query[sortDirectionKey],
                                     ignoreCase: true, out var sortDirection);
        int.TryParse(context.Request.Query[currentPageKey], out var page);
        page = page == 0 ? 1 : page;

        var result = new PagingData
        {
            SortBy = context.Request.Query[sortByKey],
            SortDirection = sortDirection,
            CurrentPage = page
        };

        return ValueTask.FromResult<PagingData?>(result);
    }
}

public enum SortDirection
{
    Default,
    Asc,
    Desc
}

自訂參數繫結與 IBindableFromHttpContext

ASP.NET Core 提供在使用 IBindableFromHttpContext<TSelf> 介面的最小 API 中支援自訂參數繫結。 此介面是使用 C# 11 的靜態抽象成員引進的,可讓您建立可直接在路由處理常式參數中從 HTTP 內容系結的類型。

public interface IBindableFromHttpContext<TSelf>
    where TSelf : class, IBindableFromHttpContext<TSelf>
{
    static abstract ValueTask<TSelf?> BindAsync(HttpContext context, ParameterInfo parameter);
}

藉由實作 IBindableFromHttpContext<TSelf> 介面,您可以建立自訂類型,從 HttpContext 處理自己的繫結邏輯。 當路由處理常式包含此類型的參數時,架構會自動呼叫靜態 BindAsync 方法來建立實例:

using CustomBindingExample;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.UseHttpsRedirection();

app.MapGet("/", () => "Hello, IBindableFromHttpContext example!");

app.MapGet("/custom-binding", (CustomBoundParameter param) =>
{
    return $"Value from custom binding: {param.Value}";
});

app.MapGet("/combined/{id}", (int id, CustomBoundParameter param) =>
{
    return $"ID: {id}, Custom Value: {param.Value}";
});

以下是從 HTTP 標頭繫結的自訂參數實作範例:

using System.Reflection;

namespace CustomBindingExample;

public class CustomBoundParameter : IBindableFromHttpContext<CustomBoundParameter>
{
    public string Value { get; init; } = default!;

    public static ValueTask<CustomBoundParameter?> BindAsync(HttpContext context, ParameterInfo parameter)
    {
        // Custom binding logic here
        // This example reads from a custom header
        var value = context.Request.Headers["X-Custom-Header"].ToString();
        
        // If no header was provided, you could fall back to a query parameter
        if (string.IsNullOrEmpty(value))
        {
            value = context.Request.Query["customValue"].ToString();
        }
        
        return ValueTask.FromResult<CustomBoundParameter?>(new CustomBoundParameter 
        {
            Value = value
        });
    }
}

您也可以在自訂繫結邏輯中實作驗證:

app.MapGet("/validated", (ValidatedParameter param) =>
{
    if (string.IsNullOrEmpty(param.Value))
    {
        return Results.BadRequest("Value cannot be empty");
    }
    
    return Results.Ok($"Validated value: {param.Value}");
});

檢視或下載範例程式碼 (如何下載)

繫結失敗

繫結失敗時,架構會記錄偵錯訊息,並根據失敗模式將各種狀態碼傳回至用戶端。

失敗模式 可為空值的參數型別 繫結來源 狀態碼
{ParameterType}.TryParse 傳回 false 是 路由/查詢/標頭 400
{ParameterType}.BindAsync 傳回 null 是 習慣 400
{ParameterType}.BindAsync 拋出 沒有關係 習慣 500
無法還原 JSON 主體 沒有關係 內文 400
錯誤的內容類型 (非 application/json) 沒有關係 內文 415

繫結優先順序

從參數判斷繫結來源的規則:

  1. 如下順序在參數上定義的明確屬性 (From* 屬性):
    1. 路由值:[FromRoute]
    2. 查詢字串:[FromQuery]
    3. 標題:[FromHeader]
    4. 本文:[FromBody]
    5. 服務:[FromServices]
    6. 參數值:[AsParameters]
  2. 特殊型別
    1. HttpContext
    2. HttpRequest (HttpContext.Request)
    3. HttpResponse (HttpContext.Response)
    4. ClaimsPrincipal (HttpContext.User)
    5. CancellationToken (HttpContext.RequestAborted)
    6. IFormFileCollection (HttpContext.Request.Form.Files)
    7. IFormFile (HttpContext.Request.Form.Files[paramName])
    8. Stream (HttpContext.Request.Body)
    9. PipeReader (HttpContext.Request.BodyReader)
  3. 參數型別具有有效的靜態 BindAsync 方法。
  4. 參數型別是字串或具有有效的靜態 TryParse 方法。
    1. 如果參數名稱存在於路由範本中。 在 app.Map("/todo/{id}", (int id) => {}); 中,id 是由路由繫結的。
    2. 繫結自查詢字串。
  5. 如果參數型別是相依性插入所提供的服務,它會使用該服務作為來源。
  6. 參數來自本文。

設定用於主體繫結的 JSON 反序列化選項

主體繫結來源會使用 System.Text.Json 來進行反序列化。 無法變更此預設值,但可以設定 JSON 序列化和還原序列化選項。

全域設定 JSON 還原序列化選項

您可以叫用 ConfigureHttpJsonOptions 來設定要全域套用至應用程式的選項。 下列範例包含公開欄位,並將 JSON 輸出格式化。

var builder = WebApplication.CreateBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options => {
    options.SerializerOptions.WriteIndented = true;
    options.SerializerOptions.IncludeFields = true;
});

var app = builder.Build();

app.MapPost("/", (Todo todo) => {
    if (todo is not null) {
        todo.Name = todo.NameField;
    }
    return todo;
});

app.Run();

class Todo {
    public string? Name { get; set; }
    public string? NameField;
    public bool IsComplete { get; set; }
}
// If the request body contains the following JSON:
//
// {"nameField":"Walk dog", "isComplete":false}
//
// The endpoint returns the following JSON:
//
// {
//    "name":"Walk dog",
//    "nameField":"Walk dog",
//    "isComplete":false
// }

由於範例程式碼會同時設定序列化和還原序列化,因此其可以讀取 NameField 並將 NameField 包含在輸出的 JSON 中。

設定端點的 JSON 還原序列化選項

ReadFromJsonAsync 具有會接受 JsonSerializerOptions 物件的多載。 下列範例包含公開欄位,並將 JSON 輸出格式化。

using System.Text.Json;

var app = WebApplication.Create();

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web) { 
    IncludeFields = true, 
    WriteIndented = true
};

app.MapPost("/", async (HttpContext context) => {
    if (context.Request.HasJsonContentType()) {
        var todo = await context.Request.ReadFromJsonAsync<Todo>(options);
        if (todo is not null) {
            todo.Name = todo.NameField;
        }
        return Results.Ok(todo);
    }
    else {
        return Results.BadRequest();
    }
});

app.Run();

class Todo
{
    public string? Name { get; set; }
    public string? NameField;
    public bool IsComplete { get; set; }
}
// If the request body contains the following JSON:
//
// {"nameField":"Walk dog", "isComplete":false}
//
// The endpoint returns the following JSON:
//
// {
//    "name":"Walk dog",
//    "isComplete":false
// }

由於上述程式碼僅會將自訂選項套用至還原序列化,因此輸出 JSON 會排除 NameField。

讀取請求本文

直接使用 HttpContext 或 HttpRequest 參數讀取要求主體:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/uploadstream", async (IConfiguration config, HttpRequest request) =>
{
    var filePath = Path.Combine(config["StoredFilesPath"], Path.GetRandomFileName());

    await using var writeStream = File.Create(filePath);
    await request.BodyReader.CopyToAsync(writeStream);
});

app.Run();

上述 程式碼: