Return a JSON string explicitly from Asp.net WEBAPI?

前端 未结 6 1262
栀梦
栀梦 2020-11-27 03:30

In Some cases I have NewtonSoft JSON.NET and in my controller I just return the Jobject from my controller and all is good.

But I have a case where I get some raw JS

6条回答
  •  醉酒成梦
    2020-11-27 03:53

    This works for me in .NET Core 3.1.

    private async Task ChannelCosmicRaysAsync(HttpRequestMessage request)
    {
        // client is HttpClient
        using var response = await client.SendAsync(request).ConfigureAwait(false); 
    
        var responseContentString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    
        Response.StatusCode = (int)response.StatusCode;
        return Content(responseContentString, "application/json");
    }
    
    public Task X()
    {
        var request = new HttpRequestMessage(HttpMethod.Post, url);
        (...)
    
        return ChannelCosmicRaysAsync(request);
    }
    

    ContentResult is Microsoft.AspNetCore.Mvc.ContentResult.

    Please note this doesn't channel headers, but in my case this is what I need.

提交回复
热议问题