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.
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.
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.