我正在尝试创建一个 ASP.NET Core 8 Minimal API 端点,并尝试让它在查询字符串参数无效时返回 HttpProblemDetails。当然,我可以实现自己的
我正在尝试创建一个 ASP.NET Core 8 Minimal API 端点,并尝试让它 HttpProblemDetails
在查询字符串参数无效时返回。当然,我可以实现自己的验证,但我正在尝试利用框架来实现这一点。
基本上,如果我有一个查询字符串参数(例如一个整数),而输入的不是有效的整数,那么我会得到一个“错误请求”,但没有任何正文。这让消费者很难理解到底出了什么问题。
下面是 C# 单元测试的再现(我使用的是 TestServer,但是使用 kestrel 时得到了相同的结果):
using System.Net.Http;
using System.Net;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Shouldly;
namespace TestProject1
{
public class HttpProblemDetailsTests
{
[Fact]
public async Task Should_return_problem_details_if_querystring_not_provided()
{
var (host, testClient) = await SetupWebApp();
var response = await testClient.GetAsync("/problem");
response.StatusCode.ShouldBe(HttpStatusCode.BadRequest);
var text = await response.Content.ReadAsStringAsync();
// Fails on this line
text.ShouldNotBeEmpty();
await host.StopAsync();
}
[Fact]
public async Task Returns_ok_if_querystring_provided()
{
var (host, testClient) = await SetupWebApp();
var response = await testClient.GetAsync("/problem?abc=123");
response.StatusCode.ShouldBe(HttpStatusCode.OK);
await host.StopAsync();
}
private async Task<(IHost host, HttpClient testClient)> SetupWebApp()
{
var b = new HostBuilder()
.ConfigureWebHost(c =>
{
c.UseTestServer();
c.ConfigureServices(services =>
{
services.AddProblemDetails();
services.AddRouting();
});
c.Configure(app =>
{
app.UseExceptionHandler();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/problem", Problem);
});
});
});
var host = await b.StartAsync();
var testClient = host.GetTestClient();
testClient.DefaultRequestHeaders.Add("Accept", "application/json");
return (host, testClient);
}
public class MyParameters
{
public int Abc { get; set; }
}
private async Task<IResult> Problem([AsParameters] MyParameters p)
{
return Results.Text("Hello, World!");
}
}
}
我还尝试了其他几种方法:
IProblemDetailsWriter
实现,但似乎没有达到这一点
[FromQuery]
而不是 [AsParameters]
。这会产生相同的结果