如何根据Web API 2 ASP.NET中收到的操作进行响应

问题描述 投票:-1回答:1

如何在Web API 2 ASP.NET中创建一个带有一个API链接的控制器,以通过该数据中的操作响应接收到的数据?

例如,我收到这些数据:

{"t":"868efd5a8917350b63dfe1bd64","action":"getExternalServicePar","args": {"id":"4247f835bb59b80"}}

现在我需要根据这个“行动”价值做出回应。如果还有其他一些动作值,例如“incrementVallet”,我需要使用不同的数据进行响应,以及来自一个API链接的所有数据等。

c# asp.net-web-api
1个回答
1
投票

显而易见的问题是“你为什么要这样做?”。为什么不使用多种方法甚至多个控制器?话虽如此,如果您真的想要,您可以执行以下操作:

public class ActionDetails 
{
    public string t { get; set; }
    public string action { get; set; }
    public ArgsContainer args { get; set; }
}
public ArgsContainer 
{
    public string id { get; set; }
}

控制器和方法:

public class MyController : ApiController
{
    // POST is not really the right choice for operations that only GET something
    // but if you want to pass an object as parameter you really don't have much of a choice
    [HttpPost]
    public HttpResponseMessage DoSomeAction(ActionDetails details)
    {
        // prepare the result content
        string jsonResult = "{}";
        switch (details.action) 
        {
            case "getExternalServicePar":
                var action1Result = GetFromSomewhere(details.args.id); // do something
                jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(action1Result);
                break;
            case "incrementVallet":
                var action2Result = ...; // do something else
                jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(action2Result);
                break;
        }
        // put the serialized object into the response (and hope the client knows what to do with it)
        var response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(jsonResult, Encoding.UTF8, "application/json");
        return response;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.