为什么json序列化在调用WebAPI时会产生错误



为了演示这个问题,我在Blazor WASM解决方案模板创建的解决方案中添加了一些POST方法。有些工作,有些没有,产生了我不理解的错误,我希望有人能教育我。

这是客户端代码:

protected override async Task OnInitializedAsync()
{
try
{
// From the Blazor template
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");
var w = new WeatherForecast();
// Works
await Http.PostAsJsonAsync<WeatherForecast>("WeatherForecast", w);

MemoryStream s = new MemoryStream();
// Generates exception: 'Timeouts are not supported on this stream.'
await Http.PostAsJsonAsync<MemoryStream>($"WeatherForecast/stream", s);

List<MemoryStream> l = new List<MemoryStream>() { new MemoryStream() };
// Generates exception: 'Timeouts are not supported on this stream.'
await Http.PostAsJsonAsync<List<MemoryStream>>($"WeatherForecast/list", l);

List<MemoryStream> m = new List<MemoryStream>();
// Works
await Http.PostAsJsonAsync<List<MemoryStream>>($"WeatherForecast/list", m);

// PdfDocument is part of the PdfSharp library which I'm using to build pdf
// files but I need to send it into the API to save it on a server.
PdfDocument doc = new PdfDocument();
// Generates exception: 'System.Security.Cryptography.Algorithms is not
// supported on this platform.'
await Http.PostAsJsonAsync<PdfDocument>("WeatherForecas/pdf", doc);
}
catch (Exception e)
{
throw;
}
}

以下是服务器端API代码:

[HttpPost]
public void Post([FromBody] WeatherForecast w)
{
if (w == null) return;
}
[HttpPost("stream")]
public void Post([FromBody] MemoryStream s)
{
if (s == null) return;
}
[HttpPost("list")]
public void Post([FromBody] List<MemoryStream> s)
{
if (s == null) return;
}
[HttpPost("pdf")]
public void Post([FromBody] PdfDocument doc)
{
if (doc == null) return;
}
}

评论显示了哪些调用有效,哪些调用无效,对于不有效的调用,错误对我来说没有意义。有人能帮助我理解为什么我不能向API发送PdfDocument吗?

提前感谢您的帮助。

生成异常:'System.Security.Cryptography.Algorithms不是此平台支持。">

这是一个已知问题:Blazor WebAssembly不支持System.Security.Cryptography API。目前还没有什么好的解决办法。

因此,作为一种解决方法,您可以尝试读取pdf内容并将内容作为字符串类型发送,或者将pdf文件发送到API方法。

相关内容

最新更新