访问控制器主体中的Web API反序列化/序列化方法

时间:2013-12-15 11:29:24

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

是否有办法在控件将反序列化/序列化{{}的同一个完全相同的方式反序列化/序列化Web API控制器主体中的JSON POST内容/响应 1}}内容/响应是否是参数/显式类型?

我的动机是,我正在尝试构建一个“神奇”的API控制器,如果开发人员没有足够的时间来构建强类型操作来访问它们,则可以快速访问我的服务命令。说我有以下行动:

JSON

是否可以做这样的事情(在伪代码中):

public Brownie Brownie(BrownieInputModel inputModel)
{
    ...
    var brownie = brownieService.GetBrownie(inputModel);
    return brownie;
}

public Pizza Pizza(PizzaInputModel inputModel)
{
    ...
    var pizza = pizzaService.GetPizza(inputModel);
    return pizza;
}

1 个答案:

答案 0 :(得分:0)

我认为HttpRequestMessageHttpResponseMessage类可以帮助您解决此问题。使用它们,您的代码可能如下所示:

public async Task<HttpResponseMessage> Post(
    string methodName, HttpRequestMessage request)
{
    HttpResponseMessage response;
    switch (methodName)
    {
        case "brownie":
            response = await HandleBrownieAsync(request);
            break;
        case "pizza":
            response = await HandlePizzaAsync(request);
            break;
        default:
            throw new NotSupportedException();
    }
    return response;
}

private async Task<HttpResponseMessage> HandleBrownieAsync(HttpRequestMessage request)
{
    var brownie = await GetRequestContentAsync<Brownie>(request);
    return await CreateJsonResponseAsync(brownie);
}

private async Task<HttpResponseMessage> HandlePizzaAsync(HttpRequestMessage request)
{
    var pizza = await GetRequestContentAsync<Pizza>(request);
    return await CreateJsonResponseAsync(pizza);
}

private async Task<T> GetRequestContentAsync<T>(HttpRequestMessage request)
{
    var contentString = await request.Content.ReadAsStringAsync();
    return await JsonConvert.DeserializeObjectAsync<T>(contentString);
}

private async Task<HttpResponseMessage> CreateJsonResponseAsync<T>(T content)
{
    var response = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new StringContent(
            await JsonConvert.SerializeObjectAsync(content),
            Encoding.UTF8,
            "application/json")
    };
    return response;
} 

如果您使用这些简化模型:

public class Brownie
{
    public bool HasNuts { get; set; }
}

public class Pizza
{
    public string CheeseType { get; set; }
}

然后你可以发出POST请求:

网址http://api.url?methodName=brownie正文{"hasNuts":true}

网址http://api.url?methodName=pizza正文{"cheeseType":"Mozzarella"}