-1

I want to accept different model type from body based on query param value.

Example:

[HttpGet]
[Route("GetSystemdetails")]
public string Getdeatils([FromBody] SystemDetail sysdetails, string type)
{
    //some code here
    string details = getdetails(sysdetails); 
}

// abc model
public class abc
{
    public int UserID { get; set; }

    public string Email { get; set; }
}

//xyz model
public class xyz
{
    public int xyzid { get; set; }

    public string systemval { get; set; }

    public string snum { get; set; }
}

type abc and xyz will have it's own model. So based on type I receive in query param I wanted to pick the model and proceed.

Sample url:

localhost/GetSystemdetails/type=abc
localhost/GetSystemdetails/type=xyz

I thought of creating a new model SystemDetail which holds these two models(xyz and abc) and based on system pick them.

I wanted to know what are possible ways to achieve this kind of requirements without creating multiple methods in controller(I don't want to change the format of the URL).

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
techresearch
  • 119
  • 3
  • 14
  • Check the post https://stackoverflow.com/questions/33924458/how-to-receive-dynamic-data-in-web-api-controller-post-method – Eanthmue Aug 22 '21 at 17:08

2 Answers2

0

That's not something that's supported out of the box. Your linked solution is probably the closest you'll get to that.

ASP.NET Core is not supposed to take values of the parameters into account when routing, except for validation.

faso
  • 679
  • 7
  • 25
0

There are several possible ways to do so

Having multiple model objects

As in the link you provided, you can declare multiple model objects. The site has given the example of

public class PostUserGCM
{
    public User User { get; set; }
    public GCM GCM { get; set; }
}

but you can use your own examples.

Base model

Your models can inherit from some base model. If you only need a single model at a time and they share some similarities, then you could just create a base model which the other two are inheriting from, be agnostic at implementation time and your use cases will mainly differ on instantiation inside the controller, while some service methods could handle other differences.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175