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

时间:2019-03-09 22:31:02

标签: c# asp.net-web-api

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

例如,我收到以下数据:

  

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

,现在我需要基于此“操作”值进行响应。如果还有其他操作值,例如“ incrementVallet”,则需要使用不同的数据以及来自一个API链接等的所有数据进行响应。

1 个答案:

答案 0 :(得分: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;
    }
}