我使用 MediatR 编写了一个简单的 API,其中包含我在网上找到的示例。它有一个 GET 和一个 POST。
API GET:
namespace API.Features.My.Queries;
[Route("api/mydata/{myid}")]
public class MyController : ControllerBase
{
private readonly IMediator _mediator;
public MyController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
public async Task<IActionResult> Get([FromRoute] long myid)
{
var response = await _mediator.Send(new MyGet.Request { Id = applicationid });
return Ok(response);
}
}
在 Blazor 页面中,我可以很好地调用 API GET:
protected override async Task OnInitializedAsync()
{
var version2 = await _apiservice.GetFromJsonAsync<MyGet>($"api/mydata/{appid}", new CancellationToken());
data = version2.Data;
editContext = new(data);
isLoading = false;
}
但是我在理解如何让该帖子发挥作用时遇到了问题。
帖子:
namespace API.Features.My.Commands;
[Route("api/mydata")]
public class MyController : ControllerBase
{
private readonly IMediator _mediator;
public MyController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> Submit([FromBody] SaveMyInfo info)
{
SaveMyInfo.Response response = await _mediator.Send(info);
return response.Success ? Ok(response) : NotFound(response);
}
}
在我的 Blazor 页面中,这就是我尝试发布更改的方式:
private async Task Submit(EditContext context)
{
var dto = new SaveMyInfo()
{
Data = (MyGet)context.Model
};
var responseMessage = string.Empty;
var version2 = await _apiservice.PostFromJsonAsync<SaveMyInfo>("api/mydata/Submit", dto, new CancellationToken());
// above gives "Bad Request"
}
服务器 API 提交上的断点永远不会达到。
我尝试阅读如何提交到 API,但我发现的示例总是传递它们用于连接的字符串,所以我只能猜测如何执行该部分。
需要更改哪些内容才能实现 POST 提交?
仅使用httpclient:
BLAZOR 中的客户:
public async Task<AuthResponse> AuthenticateUser(LoginDto loginData)
{
AuthResponse? returnResponse = null;
using (var client = new HttpClient())
{
var url = $"{_settingsService.GetApiUrlBase()}{ApiRootUrls.AuthenticateUser}";
var serializedStr = JsonSerializer.Serialize(loginData);
var response = await client.PostAsync(url, new StringContent(serializedStr, Encoding.UTF8, "application/json"));
if (response.IsSuccessStatusCode)
{
string contentStr = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
returnResponse = JsonSerializer.Deserialize<AuthResponse>(contentStr, options);
}
}
return returnResponse;
}
网络API:
[HttpPost]
[Route("Login"), AllowAnonymous]
public async Task<AuthResponse> Login([FromBody] AuthRequest request)
{
return await _userService.Login(request);
}