提问人:Marco 提问时间:10/5/2023 更新时间:10/6/2023 访问量:44
在 ASP.NET 中从 AJAX 读取 JSON
Read JSON from AJAX in ASP.NET
问:
我尝试发送到我的 JSON 文件有问题 ASP.NET
我想读取文件,输出它,并在以后相应地过滤其他函数。
我的脚本看起来像这样:
<script>
var NetworkValues = JSON.parse(localStorage.getItem("NetworkValues"));
var arpValues = JSON.parse(localStorage.getItem("arpValues"));
var addrValues = JSON.parse(localStorage.getItem("addrValues"));
var fsckValues = JSON.parse(localStorage.getItem("fsckValues"));
var vmstatValues = JSON.parse(localStorage.getItem("vmstatValues"));
var freeValues = JSON.parse(localStorage.getItem("freeValues"));
var ServiceValues = JSON.parse(localStorage.getItem("ServiceValues"));
var ProcessValues = JSON.parse(localStorage.getItem("ProcessValues"));
var topValues = JSON.parse(localStorage.getItem("topValues"));
var PortValues = JSON.parse(localStorage.getItem("PortValues"));
function sendValues()
{var NetworkOutput = NetworkValues;
var arpOutput = arpValues;
var addrOutput = addrValues;
var fsckOutput = fsckValues;
var vmstatOutput = vmstatValues;
var freeOutput = freeValues;
var serviceOutput = ServiceValues;
var processOutput = ProcessValues;
var topOutput = topValues;
var PortOutput = PortValues;
var message = document.getElementById('message');
$.ajax({
type: "POST",
url: "api/FilterSubmit",
data:
{
NetworkOutput: NetworkOutput,
arpOutput: arpOutput,
addrOutput: addrOutput,
fsckOutput: fsckOutput,
vmstatOutput: vmstatOutput,
freeOutput: freeOutput,
serviceOutput: serviceOutput,
processOutput: processOutput,
topOutput: topOutput,
PortOutput : PortOutput
},
success: function(result)
{
message.innerHTML = 'success!'
console.log(NetworkOutput)
console.log(arpOutput)
console.log(addrOutput)
console.log(fsckOutput)
console.log(vmstatOutput)
console.log(freeOutput)
console.log(processOutput)
console.log(serviceOutput)
console.log(topOutput)
console.log(PortOutput)
},
error: function(err)
{
message.innerHTML = 'failed!'
}
})
}
我在控制器内部尝试了什么:(来源:https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json)
using AspNetCore.MariaDB.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using System.Net.Http.Json;
using System.Reflection.Metadata.Ecma335;
namespace AspNetCore.MariaDB.Controllers
{
public class Buttoncontroller : Controller
{
[HttpPost]
[Route("api/FilterSubmit")]
public IActionResult ButtonClickSub()
{
static async Task<FilteredScripts> GetJsonHttpClient(string uri, HttpClient httpClient)
{
try
{
return await httpClient.GetFromJsonAsync<FilteredScripts>(uri);
}
catch (HttpRequestException) // Non success
{
Console.WriteLine("An error occurred.");
}
catch (NotSupportedException) // When content type is not valid
{
Console.WriteLine("The content type is not supported.");
}
return null;
}
return Ok();
}
}
}
private static async Task<User> GetJsonFromContent(string uri, HttpClient httpClient)
{
var request = new HttpRequestMessage(HttpMethod.Get, uri);
request.Headers.TryAddWithoutValidation("some-header", "some-value");
using var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
if (response.IsSuccessStatusCode)
{
// perhaps check some headers before deserialising
try
{
return await response.Content.ReadFromJsonAsync<User>();
}
catch (NotSupportedException) // When content type is not valid
{
Console.WriteLine("The content type is not supported.");
}
catch (JsonException) // Invalid JSON
{
Console.WriteLine("Invalid JSON.");
}
}
return null;
}
答:
0赞
Marco
10/6/2023
#1
解决方案是我忘了专门将正确的 JSON 发送回 .NET 并让内存流实际尝试读取它:
JavaScript的:
function sendValues() {
var data123 = JSON.stringify({
NetworkOutput: NetworkOutput,
arpOutput: arpOutput,
addrOutput: addrOutput,
fsckOutput: fsckOutput,
vmstatOutput: vmstatOutput,
freeOutput: freeOutput,
serviceOutput: serviceOutput,
processOutput: processOutput,
topOutput: topOutput,
PortOutput: PortOutput
});
$.ajax({
type: "POST",
url: "api/FilterSubmit",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: data123
success: ...
err: ...
})
控制器:
public class FilterSubmitData
{
public string[] NetworkOutput { get; set; }
public string[] arpOutput { get; set; }
public string[] addrOutput { get; set; }
public string[] fsckOutput { get; set; }
public string[] vmstatOutput { get; set; }
public string[] freeOutput { get; set; }
public string[] serviceOutput { get; set; }
public string[] processOutput { get; set; }
public string[] topOutput { get; set; }
public string[] PortOutput { get; set; }
}
[HttpPost]
[Route("api/FilterSubmit")]
public async Task<IActionResult> StreamWithNewtonsoftJson()
{
FilterSubmitData data;
using (var ms = new MemoryStream())
{
await Request.Body.CopyToAsync(ms);
using var streamMs = new MemoryStream(ms.ToArray());
using var streamReader = new StreamReader(streamMs);
using var jsonReader = new JsonTextReader(streamReader);
var serializer = new JsonSerializer();
data = serializer.Deserialize<FilterSubmitData>(jsonReader);
}
return Ok();
}
评论