MVC: How to Return a String as JSON

后端 未结 5 417
刺人心
刺人心 2020-11-27 16:58

In an effort to make a progress reporting process a little more reliable and decouple it from the request/response, I am performing the processing in a Windows Service and p

5条回答
  •  时光取名叫无心
    2020-11-27 17:27

    You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

    public class JsonStringResult : ContentResult
    {
        public JsonStringResult(string json)
        {
            Content = json;
            ContentType = "application/json";
        }
    }
    

    And then return it's instance:

    [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);
    }
    

提交回复
热议问题