问题:有更好的方法吗?
VB.Net
Function GuidToBase64(ByVal guid As Guid) As String
Return Convert.ToBase64String(guid.ToByteArray).Replace("/", "-").Replace("+", "_").Replace("=", "")
End Function
Function Base64ToGuid(ByVal base64 As String) As Guid
Dim guid As Guid
base64 = base64.Replace("-", "/").Replace("_", "+") & "=="
Try
guid = New Guid(Convert.FromBase64String(base64))
Catch ex As Exception
Throw New Exception("Bad Base64 conversion to GUID", ex)
End Try
Return guid
End Function
C#
public string GuidToBase64(Guid guid)
{
return Convert.ToBase64String(guid.ToByteArray()).Replace("/", "-").Replace("+", "_").Replace("=", "");
}
public Guid Base64ToGuid(string base64)
{
Guid guid = default(Guid);
base64 = base64.Replace("-", "/").Replace("_", "+") + "==";
try {
guid = new Guid(Convert.FromBase64String(base64));
}
catch (Exception ex) {
throw new Exception("Bad Base64 conversion to GUID", ex);
}
return guid;
}
.Replace("+", "_")
和相反的操作以及Replace("/", "-")
和相反的操作改为.Replace("+", "-")
和相反的操作以及Replace("/", "_")
和相反的操作。这将使编码符合RFC 4648的base64url
规范(请参见https://tools.ietf.org/html/rfc4648#section-5)。 - Kasper van den Berg