反序列化HTTP POST参数

本文关键字:参数 POST HTTP 反序列化 | 更新日期: 2023-09-27 18:06:43

我正试图找到一个更原生或更优雅的解决方案,将HTTP POST参数反序列化到各自的对象中。

目前,我将字符串转换为Dictionary,然后将其序列化为JSON,然后将其反序列化为最终对象。

示例参数字符串:TotalCost=0.01200&Direction=outbound&HangupCause=NORMAL_CLEARING&From=17272222083&Duration=40&ALegUUID=3a8687ca-ec70-11e3-a328-1f6185b4e849&BillDuration=60&BillRate=0.01200&Machine=true&To=17161234567&AnswerTime=2014-06-05+01%3A14%3A14&StartTime=2014-06-05+01%3A14%3A11&CallUUID=3a8687ca-ec70-11e3-a328-1f6185b4e849&ALegRequestUUID=79e70384-46e2-4d49-9d3e-359be9bef44b&RequestUUID=79e70384-46e2-4d49-9d3e-359be9bef44b&EndTime=2014-06-05+01%3A14%3A54&CallStatus=completed&Event=Hangup

我在WCF服务中通过REST处理这个字符串:

public void HangupCallback(Stream input)
    {
        try
        {
            var data = new StreamReader(input).ReadToEnd();
            var postParams = new Dictionary<string, string>();
            var rawParams = data.Split('&');
            foreach (var param in rawParams)
            {
                var kvPair = param.Split('=');
                var key = kvPair[0];
                var value = HttpUtility.UrlDecode(kvPair[1]);
                postParams.Add(key, value);
            }
            var jsonString = JsonConvert.SerializeObject(postParams);
            var answerRequest = JsonConvert.DeserializeObject<LogHandler.AnswerRequest>(jsonString);
            answerRequest.Timestamp = DateTime.Now;
            LogHandler.RecordCallLog(answerRequest);
        }
        catch (Exception ex)
        {
            LogHandler.RecordError(new LogHandler.StringError
            {
                Error = "HangupCallback Error" + ex.Message,
                Timestamp = DateTime.Now
            });
        }
    }

反序列化HTTP POST参数

我可以将其缩减为5行代码:

var data = new StreamReader(input).ReadToEnd();
                var dataNvc = HttpUtility.ParseQueryString(data);
                var dataCollection = dataNvc.AllKeys.ToDictionary(o => o, o => dataNvc[o]);
                var jsonString = JsonConvert.SerializeObject(dataCollection);
                var answerRequest = JsonConvert.DeserializeObject<LogHandler.AnswerRequest>(jsonString);