为什么这个HttpRequestMessage的请求URI无效?

23 浏览
0 Comments

为什么这个HttpRequestMessage的请求URI无效?

我正在尝试编写一个集成测试,测试我的应用程序的注册功能。这是控制器:

[Route("account")]
public class IdentityController : MainController
{
    // ...
    [HttpGet("signup")]
    public IActionResult SignUp()
    {
        return View();
    }
    [HttpPost("signup")]
    public async Task SignUp(UserSignUpViewModel signUp)
    {
        if (!ModelState.IsValid)
        {

我正在按照在线培训的指导进行操作,根据视频和其他示例,这是测试表单提交的正确方法:

[Fact]
public async Task Identity_CreateUser_ShouldBeSuccessful()
{
    // Arrange
    var initialResponse = await _fixture.Client.GetAsync("/account/signup");
    initialResponse.EnsureSuccessStatusCode();
    var antiForgeryToken = _fixture.GetAntiForgeryToken(await initialResponse.Content.ReadAsStringAsync());
    var postRequest = new HttpRequestMessage(HttpMethod.Post, "/account/signup")
    {
        Content = new FormUrlEncodedContent(new Dictionary
        {
            { "Name", "John Malone Doe" },
            // ...
        }
    }
    // Act
    var response = await _fixture.Client.SendAsync(postRequest);
    // ...

Rider甚至会为我自动补全路径,但是它会失败,并显示以下消息:

System.InvalidOperationException: 提供了无效的请求URI。请求URI必须是绝对URI,或者必须设置BaseAddress。

我尝试了传递完整地址"https://localhost:5001/account/signup",也尝试以以下方式编写代码:

var postRequest = new HttpRequestMessage
{
    Method = HttpMethod.Post,
    RequestUri = new Uri("https://localhost:5001/account/signup"),
    Content = new FormUrlEncodedContent(new Dictionary
    {

但都没有解决问题。

0
0 Comments

为什么这个HttpRequestMessage的请求URI无效?

看起来URI需要有一个斜杠才能有效

参考:Create new URI from Base URI and Relative Path - slash makes a difference?

而不是使用https://localhost:5001/account/signup,尝试使用https://localhost:5001/account/signup/

(第二个URI末尾有一个斜杠)

我还没有测试过这个方法。

0