gpt4 book ai didi

c# - 如何从最小的 api 操作方法获取 HttpRequest?

转载 作者:行者123 更新时间:2023-12-05 08:04:03 24 4
gpt4 key购买 nike

我编写了一个最小的 API 项目。我想从操作方法中获取 HttpRequest,但我没有获取 HttpRequest 实例:


app.MapPost("api/Create", async (RequestValidationDTO request) =>
{
try
{
HttpRequest httpRequest = Request. //There is error. How I can get Request ?
return await ApiCaller.MakeRequest<ResponseValidationDTO>(uri + "/Create", JsonConvert.SerializeObject(request), request.Token);
}
catch (Exception ex)
{
return new ResponseValidationDTO(true, "Unhandled exception has occured." + ex.Message);
}
});

最佳答案

只需在您的委托(delegate)中注入(inject) HttpRequest。

app.MapPost("api/Create", (HttpRequest request) =>
{
var userAgent = request.Headers.UserAgent;
var customHeader = request.Headers["x-custom-header"];

return Results.Ok(new { userAgent = userAgent, customHeader = customHeader });
});

参见 https://learn.microsoft.com/en-us/aspnet/core/fundamentals/use-http-context?view=aspnetcore-7.0

关于c# - 如何从最小的 api 操作方法获取 HttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70210260/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com