繁体   English   中英

如何从 ASP.NET Core Web API 返回 JSON,以便在浏览器中正确显示格式?

[英]How to return JSON from a ASP.NET Core Web API, such that it's displayed properly formatted in the browser?

我想从我的 ASP.NET Core Web API 返回 JSON,以便它在浏览器中结构化显示,而不是作为带引号的字符串:

"{\"Url\":null,\"Entry\":null,\"Type\":0,\"Priority\":false}"

为了实现这一点,我将.json扩展名映射到application/json MIME 类型,这样路径/api/zap.json返回一个 JSON 响应:

services.AddMvc(options =>
{
    options.FormatterMappings.SetMediaTypeMappingForFormat("xml", MediaTypeHeaderValue.Parse("application/xml"));
    options.FormatterMappings.SetMediaTypeMappingForFormat("json", MediaTypeHeaderValue.Parse("application/json"));
})
    .AddXmlSerializerFormatters();

Web API (GET) 将其 ZapScan 参数作为 JSON 字符串返回,因此我将返回类型设置为ActionResult<string>

// GET: api/zap.{format}
// https://localhost:5001/api/zap?url=https://example.com&entry=/&type=active&priority=true
[HttpGet, FormatFilter]
public ActionResult<string> OnGet([FromQuery] ZapScan scan)
{
    _zapDispatcher.Dispatch(scan);
    return ToJson(scan);
}

private string ToJson<T>(T obj)
{
    return JsonSerializer.Serialize(obj);
} 

扫一扫:

public class ZapScan
{
    public string Url { get; set; }
    public string Entry { get; set; }
    public ScanType Type { get; set; }
    public bool Priority { get; set; }
}

我已经验证 Web API 正确地将 HTTP Content-Type标头设置为application/json以通知浏览器其响应是 JSON 格式:

在此处输入图片说明

如何让浏览器在结构上显示我的 JSON? - 例如:

{
    "url": "null",
    "entry": "null",
    "type": 0,
    "priority": false
}

你不应该从你的方法中返回一个字符串,因为这样浏览器就会把它显示为一个字符串(当然)。 相反,使用Ok helper 方法scan对象作为实际 json 返回:

[HttpGet, FormatFilter]
public ActionResult OnGet([FromQuery] ZapScan scan)
{
    _zapDispatcher.Dispatch(scan);
    return Ok(scan);
}

首先,

return Ok(scan)将返回没有content-type string

所以你可以试试:

return Content(scan, "application/json")它将您的content-type设置为application-json

但仍然在浏览器上,它会像string一样显示,因此您可以从此链接下载(如果您使用ChromeJsonFormatter

https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=tr

编辑

var json = ToJson(scan);
return Content(json, "application/json");

无需将对象序列化为 json。 您可以直接使用以下内容:

// GET: api/zap.{format}
// https://localhost:5001/api/zap? 
url=https://example.com&entry=/&type=active&priority=true
[HttpGet, FormatFilter]
public ActionResult<string> OnGet([FromQuery] ZapScan scan)
{
   _zapDispatcher.Dispatch(scan);
    return OK(scan);
}

这也适用于匿名对象。

您还可以使用:

// GET: api/zap.{format}
// https://localhost:5001/api/zap? 
url=https://example.com&entry=/&type=active&priority=true
[HttpGet, FormatFilter]
public ActionResult<string> OnGet([FromQuery] ZapScan scan)
{
var response = Request.CreateResponse(HttpStatusCode.OK);

_zapDispatcher.Dispatch(scan);
response.Content = new StringContent(scan, Encoding.UTF8, "application/json");
return response;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM