用asp.net的json响应返回一个特定的视图。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了用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?
答案
你可以创建自定义的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();
以上是关于用asp.net的json响应返回一个特定的视图。的主要内容,如果未能解决你的问题,请参考以下文章
在 ASP.NET CORE 表单中使用 AJAX 返回 JSON
ASP.NET MVC 将部分视图呈现为字符串以返回 JSON [重复]