从Asp.net的WebAPI明确地返回一个JSON字符串? [英] Return a JSON string explicitly from Asp.net WEBAPI?

查看:475
本文介绍了从Asp.net的WebAPI明确地返回一个JSON字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些情况下,我有NewtonSoft JSON.NET和我的控制器我只是从我的控制器返回Jobject和一切都很好。

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

但我在那里我得到另一个服务生一些JSON和需要从我的WebAPI返回它的情况。在这种情况下,我不能使用NewtonSOft,但如果我能那么我会从字符串(这似乎是不必要的处理开销)一JOBJECT并返回和所有将与全世界保持健康。

But I have a case where I get some raw JSON from another service and need to return it from my webAPI. In this context I can't use NewtonSOft, but if I could then I'd create a JOBJECT from the string (which seems like unneeded processing overhead) and return that and all would be well with the world.

不过,我想简单地返回,但如果我返回字符串,则客户端接收与我为一间codeD字符串上下文JSON包装。

However, I want to return this simply, but if I return the string, then the client receives a JSON wrapper with my context as an encoded string.

我怎样才能明确地从我的WebAPI控制器方法返回一个JSON?

How can I explicitly return a JSON from my WebAPI controller method?

推荐答案

有几个选择。最简单的是有你的方法返回一个的Htt presponseMessage ,并创建该响应基于的StringContent 在你的字符串,类似于下面的code的内容:

There are a few alternatives. The simplest one is to have your method return a HttpResponseMessage, and create that response with a StringContent based on your string, something similar to the code below:

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return response;
}

这篇关于从Asp.net的WebAPI明确地返回一个JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆