首页 > 解决方案 > 使用 asp.net 返回带有 json 响应的特定视图

问题描述

我正在创建一个 asp.net Web 服务,我想使用一个带有子内容的 HTML 页面来传递给它。我在控制器中有 json 数据,但是当我返回时,我想指定使用 json 数据密封哪个视图。

[HttpPost]
public async Task<IActionResult> Create(IFormFile postedFile)
{
    byte[] data;
    using (var br = new BinaryReader(postedFile.OpenReadStream()))
    {
        data = br.ReadBytes((int)postedFile.OpenReadStream().Length);
    }

    HttpContent fileContent = new ByteArrayContent(data);
    string uirWebAPI = _configuration.GetValue<string>("Api");

    using (var client = new HttpClient())
    {
        using (var formData = new MultipartFormDataContent())
        {
            formData.Add(fileContent, "file", "File");
            client.DefaultRequestHeaders.Add("blobPath", meshFilePath);
            // calling another API to do some processing and return a json response
            var response = client.PostAsync(uirWebAPI, formData).Result;
            if (response.IsSuccessStatusCode)
            {
                using (Stream responseStream = await response.Content.ReadAsStreamAsync())
                {
                    jsonMessage = new StreamReader(responseStream).ReadToEnd();
                }
                var jsonString = await response.Content.ReadAsStringAsync();
                jsonObject = JsonConvert.DeserializeObject<object>(jsonString);
            }
            else
            {
                return null;
            }
        }
    }

    ViewData["jsonData"] = jsonString;
    return View();
}

我想做类似的事情:

var jsonData = jsonObject 
return View("myHTMLpage", jsonData);

如何使用 ASP.NET MVC 做到这一点?

标签: asp.netasp.net-mvcasp.net-web-api

解决方案


您可以将自定义 ActionResult 创建为JsonNetResult

public class JsonNetResult : ActionResult
{
    public Encoding ContentEncoding { get; set; }
    public string ContentType { get; set; }
    public object Data { get; set; }

    public JsonSerializerSettings SerializerSettings { get; set; }
    public Formatting Formatting { get; set; }

    public JsonNetResult() {
        SerializerSettings = new JsonSerializerSettings();
    }

    public override void ExecuteResult( ControllerContext context ) {
        if ( context == null )
            throw new ArgumentNullException( "context" );

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = !string.IsNullOrEmpty( ContentType )
            ? ContentType
            : "application/json";

        if ( ContentEncoding != null )
            response.ContentEncoding = ContentEncoding;

        if ( Data != null ) {
            JsonTextWriter writer = new JsonTextWriter( response.Output ) { Formatting = Formatting };

            JsonSerializer serializer = JsonSerializer.Create( SerializerSettings );
            serializer.Serialize( writer, Data );

            writer.Flush();
        }
    }
}

推荐阅读