6

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?

SuperJMN
  • 13,110
  • 16
  • 86
  • 185

3 Answers3

6

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

Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
0

I think your problem is model binding. The way refit serializes your object and how API serialization/deserialization works should match. Refit has serialization settings, you need to adjust. can you look it that?

Take a look at : https://reactiveui.github.io/refit/

Under JSON content section.

Similarly, your API should work with the same serialization settings. You can configure it at your services in Startup.cs

DarthVader
  • 52,984
  • 76
  • 209
  • 300
-2

The solution was to implement IFormattable. Found that after going through the Refit source code, weird it's not documented.

nicks
  • 2,161
  • 8
  • 49
  • 101