简体   繁体   English

将可为空的 Guid 发送到 WebApi Asp.net

[英]Send nullable Guid to WebApi Asp.net

I have a web api end point with the declaration:我有一个带有声明的 web api 端点:

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

Sometimes I want to send null for the first parameter.有时我想发送null作为第一个参数。 I read on one of the threads to send it as "null" in a string quotation.我在其中一个线程上阅读以在字符串引号中将其作为"null"发送。 However I'm getting:但是我得到:

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)

I tried to look it up in https://github.com/dotnet/corefx/blob/master/src/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs#L940 but it appears that the Json Parser is not handling this null case.我试图在https://github.com/dotnet/corefx/blob/master/src/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.TryGet.cs#L940中查找它似乎 Json 解析器没有处理这个null案例。 How can i achieve this, my second best option is to send an empty Guid 000-00000000-00-000... from the javascript client, and check in the web api controller, but feels like a hack. How can i achieve this, my second best option is to send an empty Guid 000-00000000-00-000... from the javascript client, and check in the web api controller, but feels like a hack.

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

This will allow setting fingerprint to null while leaving property_id as a required argument to your method.这将允许将fingerprint设置为 null,同时将property_id作为方法的必需参数。

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

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