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

How do I convert a string into an HTTP Response in C#?

{
    "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@example.com,,,,,,,,,0.00,0.00,0.00,FALSE,none,,,,,,,,,,,,,,XXXX1234,Visa,,,,,,,,,,,,,,,,,",
    "messages": {
        "resultCode": "Error",
        "message": [
            {
                "code": "E00039",
                "text": "A duplicate customer payment profile already exists."
            }
        ]
    }
}

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

您正在尝试将其转换为 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 就足够了。