首页 > 解决方案 > 将可为空的 Guid 发送到 WebApi Asp.net

问题描述

我有一个带有声明的 web api 端点:

public async Task VisitorConnected(Guid? fingerprint, long property_id)

有时我想发送null第一个参数。我在其中一个线程上阅读以将其作为"null"字符串引用发送。但是我得到:

System.IO.InvalidDataException: Error binding arguments. Make sure that the types of the provided values match the types of the hub method being invoked.
 ---> System.FormatException: The JSON value is not in a supported Guid format.
   at System.Text.Json.Utf8JsonReader.GetGuid()
   at System.Text.Json.Serialization.Converters.JsonConverterGuid.Read(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options)
   at System.Text.Json.JsonPropertyInfoNullable`2.OnRead(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)
   at System.Text.Json.JsonPropertyInfo.Read(JsonTokenType tokenType, ReadStack& state, Utf8JsonReader& reader)

我试图在https://github.com/dotnet/corefx/blob/master/src/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs#L940中查找它似乎 Json Parser 没有处理这种null情况。我该如何实现这一点,我的第二个最佳选择是从 javascript 客户端发送一个空的 Guid 000-00000000-00-000...,然后签入 web api 控制器,但感觉就像一个黑客。

标签: c#asp.netasp.net-coreasp.net-web-api

解决方案


尝试将您的 Web API 方法更改为以下内容:
public async Task VisitorConnected(long property_id, Guid? fingerprint = null)

这将允许设置fingerprint为 null,同时将property_id其作为方法的必需参数。


推荐阅读