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

Cod*_*ior 63 asp.net-mvc json

为了使进度报告过程更可靠并将其与请求/响应分离,我正在Windows服务中执行处理并将预期的响应持久保存到文件中.当客户端开始轮询更新时,意图是控制器将文件的内容(无论它们是什么)作为JSON字符串返回.

该文件的内容已预先序列化为JSON.这是为了确保没有任何阻碍响应的方式.不需要处理(没有将文件内容读入字符串并返回它)以获得响应.

我最初虽然这很简单,但事实并非如此.

目前我的控制器方法看起来如此:

调节器

更新

[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);
}
Run Code Online (Sandbox Code Playgroud)

Fiddler将此作为原始回复

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\":[]}"
Run Code Online (Sandbox Code Playgroud)

AJAX

更新

以下内容可能会在以后更改,但是现在,当我生成响应类并将其作为JSON返回时,这就像普通人一样.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Dr.*_*ice 115

我认为,问题在于Json操作结果旨在获取对象(您的模型)并使用内容作为模型对象的JSON格式数据创建HTTP响应.

但是,传递给控制器​​的Json方法的是JSON格式的字符串对象,因此它将字符串对象 "序列化"为JSON,这就是为什么HTTP响应的内容被双引号括起来(I' m假设这是问题).

我觉得你可以考虑使用内容的行动结果来替代JSON动作的结果,因为你实际上已经有可用的HTTP响应的原始内容.

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
Run Code Online (Sandbox Code Playgroud)

另一个替代方法是将服务中的JSON结果反序列化为对象,然后将该对象传递给控制器​​的Json方法,但缺点是您将反序列化然后重新序列化数据,这可能是不必要的为了你的目的.

  • +1:您还需要将结果的ContentType属性设置为"application/json",因为这是JsonResult自动执行的操作. (4认同)

Dmi*_*sev 40

您只需返回标准ContentResult并将ContentType设置为"application/json".您可以为它创建自定义ActionResult:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后返回它的实例:

[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);
}
Run Code Online (Sandbox Code Playgroud)


Iva*_*cía 8

是的,就是这样,没有其他问题,为了避免原始字符串 json,就是这样。

    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
        };
    } 
Run Code Online (Sandbox Code Playgroud)

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