简体   繁体   中英

ASP.NET Web API get dto from body with interface type

I want to create a [HTTPPOST] controller method. As you can see below, I have a class with two properties of type IBaseClass . That's because these properties can be either of type MyClassA or MyClassB .

I got my dtos like this:

public MyDtoToGet {
    public int MyId {get;set;}
    public IBaseClass base1 {get;set;}
    public IBaseClass base2 {get;set;}
}

public interface IBaseClass {
    public int Id {get;set;}
}

public class MyClassA : IBaseClass {
    public int Id {get;set;}
    public string PropertyA {get;set;}
}

public class MyClassB : IBaseClass {
    public int Id {get;set;}
    public int PropertyB {get;set;}
}

And my controller looks like this:

[HttpPost]
public ActionResult Post([FromBody]MyDtoToGet myDtoToGet)
{
    // Problem here -> myDtoToGet is null!
}

I guess that there is a problem deserializing the IBaseClass properties of MyDtoToGet in the JSON. A [HTTPGET] works fine. Since I've never done something like this before I got no clue what I do wrong...

Thanks in advance: :)

You dont need to make your DTO class very complex. Since you want to make your DTO with Properties in Other classes make it as following. You are going to use the DTO for reading the data from user (Client side Technologies / Postman) You dont need the id field.

public MyDtoToGet {
public string PropertyA {get;set;} 
public string PropertyA {get;set;} 
}

Extra: Test it with Postman, Req Type should post and body of Type JSON and send the following data

{
 "propertyA": "GreatWord",
 "propertyB": "ItIsEasy"
}

and then you can see that the data is arrived.

If you want to get data in the form of MyDtoToGet class. The JSON should be in following format. The reason you got null is because of invalid json format being passed.

{
    "MyId": 1,
    "base1": {
        "Id": 2,
        "PropertyA": "any string"
    },
    "base2": {
        "Id": 3,
        "PropertyA": "any string"
    }
}

Make sure to not forget to set 'content-type: application/json' header to your request, and that json format of you data matches to your DTO.

Best to try with simple DTO for start.

I solved it by accepting an JObject instead of an MyDtoToGet from the JSON body. Then I manually converted the type of the interfaces to the correct type. At the end I created a new object and added the converted objects.

Thanks anyways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM