.net core 从控制器返回的响应中的某些内容已意外更改

.net core some content in response returned from controller has been changed unexpectedly

我从 http 客户端 sendasync 方法返回了一些数据,类似于以下内容:

using (var response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
    var stream = await response.Content.ReadAsStreamAsync();
    using var streamReader = new StreamReader(stream, Encoding.UTF8);
    var message = await streamReader.ReadToEndAsync();

    return new ContentResult
    {
        Content = message,
        ContentType = response.Content.Headers.ContentType?.ToString(),
        StatusCode = (int)response.StatusCode
    };
}

我收到的信息中包含

等字符

"xœ½�Y�·€ßØÿÐOÁL€m5Ùì+0èrà ¶eK‰ä<ŒW#k�Ý•¢9°}X<º9MV±†š‚FÇ«ªy|,’ÅÞêÑ‹ê‹/}óôëgUóå—Õ“gO«'¯./}%©ªWo//DÕè_¢mWOcÕOCÝ÷Õ«»Ë‹¦–íT5u34½þ£k‡êã/Éÿþáo—¯7/>¾ÿ°m7ïvúó¶Ú^µ›Ç‡ÃîúÝÝþþðP=Ûv7·Û+¹yØþ»zõ÷Ë‹çÚðÆ» †¾táõ¦ d«çß<­ªà‘DðH^É ëF?Z?hQ%ÿ¹¼èûz최k)+ÙŽõ4T¢¯›±ú¸¿¼øñÏÕ½ŒIgŒ[Ö׳Pus\ÕÞÅNÔ­²U]AÅV®¡æÞoÕæƒþ

ìLµ™ýVÿ{w·�6û𡾿¼ø|·Ä0Ôㄹµ2÷ýR“mÓ×­8¡&Û¥&Yeq—[!j5h—ÛZö9—O3'+!W¶ºZµ˜­gŸîî¶WÝæ·­h6Õãí4Ÿn/óq{£[íz·í7‡›÷ð÷ðq^÷””fðüU¡&QwLSß'Æ­rÀÓ½¶µã½ª[Í5ÚpâíŸ9_›>o¾vOq$Ð6]=¶Aù¦k [¨ŠNuµÃ4�§JøÇ°Õm¾Z*;ôs"

然而,当我的控制器 returns 内容发生变化时,现在看起来像:

x���Y�������O�L�m5��+0�r� �eK��<�W#k�ݕ�9�}X<�9MV����F���y|,����ы�/}���gU��ՓgO�'�./}%��Wo//D��_�mWOc�OC��ի�ˋ���T5u34���k���/����o��7/>���m7�v���^��LJ��������P=�v7��+�y���z��ˋ���ƻ���t��� d���<����D�H^� �F?Z?

控制器中的代码类似于:

public async Task<ContentResult> MyAction()
{
    string request = await ReadRequestBody();
    ContentResult result = await _service.Post(request);
    return result;
}

单步执行代码时,我可以看到内容结果中有正确的值。 有没有人以前见过这个并且知道如何解决这个问题以便返回内容不变。

试试这个,

public async Task<HttpResponseMessage> Post(string requestBody, string action)
{
    using (var request = new HttpRequestMessage(HttpMethod.Post, ""))
    {
        request.Headers.Add("SOAPAction", action);
        request.Content = new StringContent(requestBody, Encoding.UTF8, "text/xml");
        var response = await Client.SendAsync(request);
        return response;
    }
}

然后在你的控制器中return它是这样的

var result = await _service.Post(requestBody, action);

var stream = await result.Content.ReadAsStreamAsync();
await stream.CopyToAsync(HttpContext.Response.Body);