Skip to content
Advertisement

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

I’ve built different get methods using body request to select an id (with raw json). However, as I learned that get methods doesn’t support body request, I would like to change so that I can use params in postman insted. However, when I do it now, I get an 415 Unsupported Media Type.

Here’s the method:

    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;
    }

Controller:

 [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();
        }

Interface class:

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

Before I sent requests in the body like:

{
    "rentreasonId": "40"
}

But I would like to send it in the params insted so for example:

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

Anyone know how to achive this?

Advertisement

Answer

You can have method parameters bound to query parameters by using the [FromQuery] Attribute.

In your case, it should look something like this:

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

which will enable you to use <your controller path>/rentReason?rentreasonId=40


However, I’d recommend to use route parameters for this:

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

Which will get you something like <authority>/your/api/route/rentreason/40.

For reference: FromRouteAttribute

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement