asp.net - 使用 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();
}
}
}
推荐阅读
- python - 如何在熊猫数据框中生成字母数字固定长度列
- typescript - 通过 toDataUrl() 渲染图像的 fabric.js 自定义大小
- unity3d - Rider 2019.1 - 从命令行启动代码检查
- android - 删除应用程序,因为它违反了设备和网络滥用政策
- javascript - 使用文本字段移动 div 内联
- android - 集成Sqlcipher时,Android Native Application在少数手机(Oppo,Mi)上崩溃,为什么?
- ruby-on-rails - 思考狮身人面像的自动完成
- laravel - Laravel - 聚合和中的基数违规错误
- php - symfony 4 - 形式约束 - 图像不工作
- batch-file - 通过将 .bat 脚本中的所有“&”字符替换为另一个字符来编辑字符串