如何将 JSON 数据发布到 ASP.NET Web API?

问题描述 投票:0回答:1

我的 .NET MAUI 应用程序收到以下客户端请求:

var authenticator = new JwtAuthenticator(_authService.GetToken());

var options = new RestClientOptions(Settings.Instance.CompanyURL)
{
    Authenticator = authenticator
};

var client = new RestClient(options);
var request = new RestRequest("/api/MyController MyAction");
request.AddHeader("Content-Type", "application/json");
request.AddJsonBody(logData);

RestResponse response = client.Post(request);

端点看起来像这样:

[Route("api/[controller] [action]")]
[ApiController]
public class MyController : ControllerBase
{
    private IHttpContextAccessor _httpContextAccessor;
    private ISaveData _saveData;

    public ClientLogsController(IHttpContextAccessor httpContextAccessor, ISaveData saveData)
    {
        _httpContextAccessor = httpContextAccessor;
        _saveData = saveData;
    }

    [HttpPost]
    [Authorize]
    public IActionResult MyAction([FromBody] string data)
    {
        _saveData.SaveData(data, _httpContextAccessor);

        return Ok();
    }
}

当我从 MAUI 应用程序发出请求时,我在

RestResponse response = client.Post(request);
处收到以下错误:

System.Net.Http.HttpRequestException:请求失败,状态代码为 BadRequest

错误来自客户端应用程序,因为它在 Postman 中工作正常。我正在努力寻找问题所在。

c# .net-core asp.net-web-api maui
1个回答
0
投票

您似乎错误地定义了控制器路由。 在控制器和客户端中,删除空格并使用 / 代替: “/api/MyController/MyAction”

© www.soinside.com 2019 - 2024. All rights reserved.