Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refit [FromQuery] with custom class not getting values

I'm having a problem with a Get method in my Web API: The API gets the object but with the default values.

For instance:

myRefitClient.GetSummary(new MyClass() { Prop = 1 });

The Web API correctly receives a MyClass instance, but Prop is 0!

This is all that I have:

The Get method (Controller in the Web API):

[HttpGet]
async Task<ActionResult> Get([FromQuery]MyClass req)

MyClass is:

public class MyClass
{
    public int Prop { get; set; }
}

and my Web API interface for Refit is:

public interface IMyWebApi
{
    [Get("/api/mycontroller")]
    Task<PositionSummary> GetSummary(MyClass req);
}

So, as I said, upon the call:

service.GetSummary(new MyClass() { Prop = 1 });

I'm getting a MyClass Instance in my Controller, but Prop is 0, instead of 1.

What am I doing wrong?

like image 927
SuperJMN Avatar asked Oct 17 '22 05:10

SuperJMN


1 Answers

To force ASP.NET Web API (not ASP.NET Core) to read a complex type from the URI, add the [FromUri] attribute to the parameter:

[HttpGet]
public async Task<ActionResult> Get([FromUri]MyClass req)

If you are using ASP.NET Core then use [FromQuery] attribute

[HttpGet]
public async Task<ActionResult> Get([FromQuery]MyClass req)

I'm getting a MyClass Instance in my Controller, but Prop is 0, instead of 1.

If /api/mycontroller is set as launchUrl in launchSettings.json then you will get MyClass Instance with Prop = 0 at the start of application. But next call using Refit should pass parameters

like image 173
Roman Marusyk Avatar answered Nov 15 '22 05:11

Roman Marusyk