如何在C#中将字符串转换为HTTP响应?

问题描述 投票:3回答:1
{
    "AdditionalProcessCardSwipeResponseData": null,
    "CustomerTransactionID": "",
    "ProcessCardSwipeOutputs": [
        {
            "AdditionalProcessCardSwipeResponseData": null,
            "CardSwipeOutput": {
                "AdditionalOutputData": [
                    {
                        "key": "CardType",
                        "value": "VISA"
                    }
                ],
                "CardID": "abcdefghijk",
                "IsReplay": false,
                "MagnePrintScore": 0.12345,
                "PanLast4": "1234"
            },
            "CustomerTransactionID": "",
            "DecryptForwardFaultException": null,
            "MagTranID": "2c3b08e9-b628-4f3c-a8ad-1ac1d57c1698",
            "PayloadResponse": "HTTP\/1.1 200 OKPragma: no-cache\u000aX-OPNET-Transaction-Trace: a2_8bfb4474-c9fb-4257-b914-8411770544e4-22192-26834262\u000aAccess-Control-Allow-Credentials: true\u000aAccess-Control-Allow-Headers: x-requested-with,cache-control,content-type,origin,method,SOAPAction\u000aAccess-Control-Allow-Methods: PUT,OPTIONS,POST,GET\u000aAccess-Control-Allow-Origin: *\u000aStrict-Transport-Security: max-age=31536000\u000aX-Cnection: close\u000aContent-Length: 328\u000aCache-Control: no-store\u000aContent-Type: application\/json; charset=utf-8\u000aDate: Thu, 26 Dec 2019 16:05:35 GMT\u000a\u000a&{\"messages\":{\"resultCode\":\"Error\",\"message\":[{\"code\":\"E00003\",\"text\":\"The 'AnetApi\/xml\/v1\/schema\/AnetApiSchema.xsd:customerProfileId' element is invalid - The value 'customer_profile_id' is invalid according to its datatype 'AnetApi\/xml\/v1\/schema\/AnetApiSchema.xsd:numericString' - The Pattern constraint failed.\"}]}}",
            "PayloadToken": "ADFASDFASDFASDFASDFASFADSFF",
            "TransactionUTCTimestamp": "2019-12-26 16:05:35Z"
        }
    ]
}

如何将为“ PayloadResponse”返回的字符串转换为HTTPResponse?我尝试了以下操作,但无法检索响应的正文:

var response = JObject.Parse(await httpResponseMessage.Content.ReadAsStringAsync());
var payloadResponse = response["ProcessCardSwipeOutputs"][0]["PayloadResponse"];


var msg = new HttpResponseMessage
{
   Content = new StringContent(payloadResponse.ToString(), Encoding.UTF8, "application/json")
};

这是我想转换为HttpResponse的PayloadResponse的内容,以便我可以以一种简洁的方式解析出响应主体:

HTTP/1.1 200 OKPragma: no-cache
X-OPNET-Transaction-Trace: a2_cadac737-0b60-45f5-9d5a-4d540c0975a0-7760-47076038
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: x-requested-with,cache-control,content-type,origin,method,SOAPAction
Access-Control-Allow-Methods: PUT,OPTIONS,POST,GET
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000
X-Cnection: close
Content-Length: 530
Cache-Control: no-store
Content-Type: application/json; charset=utf-8
Date: Thu,
26 Dec 2019 21: 46: 56 GMT

&{
    "customerProfileId": "45345345345",
    "customerPaymentProfileId": "123123123",
    "validationDirectResponse": "1,1,1,(TESTMODE) This transaction has been approved.,000000,P,0,none,Test transaction for ValidateCustomerPaymentProfile.,1.00,CC,auth_only,none,John,Doe,,2020 Vision St,Somewhere,CA,90028,USA,,,[email protected],,,,,,,,,0.00,0.00,0.00,FALSE,none,,,,,,,,,,,,,,XXXX1234,Visa,,,,,,,,,,,,,,,,,",
    "messages": {
        "resultCode": "Error",
        "message": [
            {
                "code": "E00039",
                "text": "A duplicate customer payment profile already exists."
            }
        ]
    }
}
c# .net httpresponse httpresponsemessage
1个回答
0
投票

如果我理解正确,您只想“ 以一种干净的方式解析响应主体”。

您正在尝试将其转换为HttpResponseMessage,因为您认为这将为您准备好一切。这是一种干扰,听起来好像您想要创建一个响应并将其转发,但是您真正想要的只是将有效载荷解析为可用格式。

如果我错了,请纠正我。

要解析该有效负载,您可以在换行符(/u000a)上拆分该字符串,删除多余的&并解析json。

var splitResponse = payloadResponse.ToString().Split(new char[] { '\u000a' });

string body = splitResponse.Last().Substring(1);

JObject job = JObject.Parse(body);

// example
Console.WriteLine(job["messages"]["message"][0]["text"]);

我没有提供可将该json反序列化的类,因为它是一条错误消息,并且我假设您将不会总是在处理错误。成功响应可能是不同的模式。从您提供的信息中我不知道如何为此设计类,但是也许使用JObject就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.