获取在邮递员中接受参数的请求,当前发送不支持的媒体类型错误

get request to accepts params in postman, currently sends a unsupported media type error

我构建了不同的 get 方法,使用正文请求 select 一个 id(使用原始 json)。但是,当我了解到 get 方法不支持正文请求时,我想更改以便我可以在邮递员中使用参数。但是,当我现在这样做时,我得到一个 415 Unsupported Media Type。

方法如下:

    public async Task<IEnumerable<RentReason>> getRentReason(RentReason model)
    {  
        var parameters = new DynamicParameters();
        parameters.Add("@rentId", model.rentreasonId);
        var getAllRentReason = await _sqlconnection.QueryAsync<RentReason>($@"SELECT 
        CostItem.ID as rentreasonId,
        CostItem.CostItemTypeID as claimReason,
        RequestRentServiceReason.Name as rentReason, 
        RequestRentServiceCartype.Name as RentServiceCarTypeID, 
        DateFrom, DateTo, Price as totalPrice 
        FROM CostItem 
        INNER JOIN RequestRentServiceReason ON CostItem.RentReasonID = RequestRentServiceReason.ID
        INNER JOIN RequestRentServiceCartype ON CostItem.RentServiceCartypeID = RequestRentServiceCartype.ID
        WHERE CostItem.ID = @rentId", parameters);
        return getAllRentReason;
    }

控制器:

 [HttpGet]
        public async Task<IActionResult> getRentReason(RentReason model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            try
            {
                var list = await _request.getRentReason(model);
                return Ok(list);
            }
            catch (Exception ex)
            {

                return BadRequest(ex.Message);
            }
            return Ok();
        }

接口class:

Task<IEnumerable<RentReason>> getRentReason(RentReason model);

在我发送正文请求之前:

{
    "rentreasonId": "40"
}

但我想在设置的参数中发送它,例如:

https://localhost/Request/getRentReason?rentreasonId=40

有人知道如何实现吗?

您可以使用 [FromQuery] 属性将方法参数绑定到查询参数。

在你的情况下,它应该看起来像这样:

public async Task<IActionResult> getRentReason([FromQuery] int rentreasonId)

这将使您能够使用 <your controller path>/rentReason?rentreasonId=40


但是,我建议为此使用路由参数:

[HttpGet("/your/api/route/rentreason/{rentreasonId}")]
public async Task<IActionResult> getRentReason([FromRoute] int rentreasonId)

这会让你得到类似 <authority>/your/api/route/rentreason/40 的东西。

供参考:FromRouteAttribute