首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >MVC:如何将字符串作为JSON返回

MVC:如何将字符串作为JSON返回
EN

Stack Overflow用户
提问于 2012-03-20 04:50:08
回答 5查看 116.7K关注 0票数 71

为了使进度报告过程更可靠,并使其与请求/响应分离,我在Windows服务中执行处理,并将预期的响应持久化到文件中。当客户端开始轮询更新时,目的是让控制器以JSON字符串的形式返回文件的内容。

该文件的内容被预序列化为JSON。这是为了确保响应过程中没有任何障碍。不需要进行任何处理(只需将文件内容读入字符串并返回)即可获得响应。

我最初认为这将是相当简单的,但事实并非如此。

目前我的控制器方法看起来是这样的:

控制器

已更新

代码语言:javascript
复制
[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string path = Properties.Settings.Default.ResponsePath;
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = System.IO.File.ReadAllText(path);

    return this.Json(returntext);
}

Fiddler将此作为原始响应返回

代码语言:javascript
复制
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 19 Mar 2012 20:30:05 GMT
X-AspNet-Version: 4.0.30319
X-AspNetMvc-Version: 3.0
Cache-Control: private
Content-Type: application/json; charset=utf-8
Content-Length: 81
Connection: Close

"{\"StopPolling\":false,\"BatchSearchProgressReports\":[],\"MemberStatuses\":[]}"

AJAX

已更新

下面的内容可能会在以后更改,但现在,当我生成response类并像普通人一样将其作为JSON返回时,这是有效的。

代码语言:javascript
复制
this.CheckForUpdate = function () {
var parent = this;

if (this.BatchSearchId != null && WorkflowState.SelectedSearchList != "") {
    showAjaxLoader = false;
    if (progressPending != true) {
        progressPending = true;
        $.ajax({
            url: WorkflowState.UpdateBatchLink + "?SearchListID=" + WorkflowState.SelectedSearchList,
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            cache: false,
            success: function (data) {
                for (var i = 0; i < data.MemberStatuses.length; i++) {
                    var response = data.MemberStatuses[i];
                    parent.UpdateCellStatus(response);
                }
                if (data.StopPolling = true) {
                    parent.StopPullingForUpdates();
                }
                showAjaxLoader = true;
            }
        });
        progressPending = false;
    }
}
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-03-20 05:01:59

我认为,问题在于Json操作结果旨在获取一个对象(您的模型)并创建一个HTTP响应,其中的内容是来自您的模型对象的JSON格式的数据。

不过,传递给控制器的Json方法的是一个JSON格式的string对象,因此它将string对象“序列化”为JSON,这就是HTTP响应的内容被双引号括起来的原因(我假设这就是问题所在)。

我认为您可以考虑使用Content操作结果作为Json操作结果的替代方法,因为您基本上已经拥有了HTTP响应的原始内容。

代码语言:javascript
复制
return this.Content(returntext, "application/json");
// not sure off-hand if you should also specify "charset=utf-8" here, 
//  or if that is done automatically

另一种选择是将来自服务的JSON结果反序列化为一个对象,然后将该对象传递给控制器的Json方法,但这样做的缺点是,您需要反序列化数据,然后重新序列化数据,这对于您的目的来说可能是不必要的。

票数 139
EN

Stack Overflow用户

发布于 2012-03-20 05:07:25

您只需返回标准应用程序并将ContentType设置为“ContentResult /json”即可。您可以为其创建自定义ActionResult:

代码语言:javascript
复制
public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

然后返回它的实例:

代码语言:javascript
复制
[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}
票数 45
EN

Stack Overflow用户

发布于 2017-06-13 00:59:57

是的,这就是它,没有更多的问题,为了避免原始字符串json,这就是它。

代码语言:javascript
复制
    public ActionResult GetJson()
    {
        var json = System.IO.File.ReadAllText(
            Server.MapPath(@"~/App_Data/content.json"));

        return new ContentResult
        {
            Content = json,
            ContentType = "application/json",
            ContentEncoding = Encoding.UTF8
        };
    } 

注意:请注意,JsonResult的方法返回类型对我不起作用,因为JsonResultContentResult都继承了ActionResult,但它们之间没有关系。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9777731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档