简体   繁体   中英

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"
        }
    ]
}

How do I convert the string returned for "PayloadResponse" to a HTTPResponse? I've tried the following but am not able to retrieve the body of the response:

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")
};

This is the content of the PayloadResponse I want to convert to an HttpResponse so that I can parse out the response body in a clean way:

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."
            }
        ]
    }
}

If I understand correctly you just want to " parse out the response body in a clean way ".

You are trying to convert this to an HttpResponseMessage because you think that will line everything up for you. This is a distraction, it makes it sound like you want to create a response and forward it on, but all you really want is the payload to be parsed into a usable format.

Correct me if I'm wrong.

To parse out that payload you can split that string on the newline character ( /u000a ), remove the extraneous & and parse the 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"]);

I did not provide classes that you can deserialize this json into because it is an error message and I assume you won't always be dealing with an error. A success response would probably be a different schema. I can't know how to design classes for this from the information you have provided but maybe working with the JObject is adequate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM