1

I am trying to migrate an old api to webapi. Problem is that experience is limited so I am here asking this question.

The current api accepts a json payload in a single url. Say /api. The json payload has the following structure

{'action': 'login', 'username': 'user1', 'password': 'password1'}

This should have been a route like /api/login so I could do something like

[Route("api/Login")]
public string Login(Login login)

and define a class for deserialization like

class Login
{
    public string username{ get; set; }
    public string password{ get; set; }
}

So I made a Route to accept [FromBody] payload and I am stuck finding a way to deserialize the object in a nice way depending on the action.

Every payload could be a valid serializable object with the way I describe If the action key is removed from the payload.

Any suggestions that will not generate ugly code? Please no api rewrite or v2 answer. If I could do it I wouldn't ask this.

1 Answer 1

3

Assuming that "action" exists in every payload you could deserialise to the dynamic type then check the action value and then cast the payload again to a specific type once you know what this action is. This addresses the particular issue you are having.

So your endpoint code could look something like this:

//this is written from memory, so could have mistakes ...
var deserialisedData = Newtonsoft.Json.JsonConvert.DeserialiseObject<dynamic>(payload);

switch ( deserialisedData.action )
{
     case "someValue":
          //here you know what the action is so hopefully what kind of payload to              expect
          var properType = payload as SomeProperType
     break;
}

if you were to consider creating a brand new, proper api, you could start introducing endpoints for each action, one at a time. It's much better to separate them than to have one endpoint to rule them all, so to speak.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.