|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | +// #see https://github.com/NuGet/NuGet.Server |
| 4 | +using System; |
| 5 | +using Newtonsoft.Json; |
| 6 | + |
| 7 | +namespace OmniSharp.Extensions.LanguageServer.Protocol.Serialization.Converters |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// This is necessary because Newtonsoft.Json creates <see cref="Uri"/> instances with |
| 11 | + /// <see cref="UriKind.RelativeOrAbsolute"/> which treats UNC paths as relative. NuGet.Core uses |
| 12 | + /// <see cref="UriKind.Absolute"/> which treats UNC paths as absolute. For more details, see: |
| 13 | + /// https://github.com/JamesNK/Newtonsoft.Json/issues/2128 |
| 14 | + /// </summary> |
| 15 | + class AbsoluteUriConverter : JsonConverter<Uri> |
| 16 | + { |
| 17 | + public override Uri ReadJson(JsonReader reader, Type objectType, Uri existingValue, bool hasExistingValue, JsonSerializer serializer) |
| 18 | + { |
| 19 | + if (reader.TokenType == JsonToken.Null) |
| 20 | + { |
| 21 | + return null; |
| 22 | + } |
| 23 | + else if (reader.TokenType == JsonToken.String) |
| 24 | + { |
| 25 | + var uri = new Uri((string)reader.Value, UriKind.RelativeOrAbsolute); |
| 26 | + if (!uri.IsAbsoluteUri) |
| 27 | + { |
| 28 | + throw new JsonSerializationException($"The Uri must be absolute. Given: {reader.Value}"); |
| 29 | + } |
| 30 | + return uri; |
| 31 | + } |
| 32 | + |
| 33 | + throw new JsonSerializationException("The JSON value must be a string."); |
| 34 | + } |
| 35 | + |
| 36 | + public override void WriteJson(JsonWriter writer, Uri value, JsonSerializer serializer) |
| 37 | + { |
| 38 | + if (value == null) |
| 39 | + { |
| 40 | + writer.WriteNull(); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + if (!(value is Uri uriValue)) |
| 45 | + { |
| 46 | + throw new JsonSerializationException("The value must be a URI."); |
| 47 | + } |
| 48 | + |
| 49 | + if (!uriValue.IsAbsoluteUri) |
| 50 | + { |
| 51 | + throw new JsonSerializationException("The URI value must be an absolute Uri. Relative URI instances are not allowed."); |
| 52 | + } |
| 53 | + |
| 54 | + writer.WriteValue(uriValue.ToString()); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments