私はUnity Free + NodeJSを使用して、私の仲間と小さなプロジェクトをコーディングしています。C#長いBase64文字列をデコードする
サーバー用NodeJs、およびクライアント用Unity。
有効なログインデータを入力した場合、サーバーはnjwtを使用してjwtを返します。njwtはさまざまなオンラインツールとc#でデコードできます。
ただし、この行:byte[] _dec = Convert.FromBase64String(part);
はエラーを返さず、さらにコードの実行を防止します。そして私は理由を知らない。
ここでは、何が起こっているのかを理解するためのサンプルがあります。
LoginMenu.cs
ws.OnMessage += (sender, e) => {
JObject res = JObject.Parse(e.Data);
switch ((string)res["type"])
{
// If we get a token from the server
// login was successful
case "jwt":
Debug.Log("Res was JWT");
UserAccountManager.instance.LogIn((string)res["jwt"]);
Debug.LogWarning("FINISHED");
break;
// Only 1 case for now
}
};
UserAccountManager.cs
public static UserAccountManager instance;
void Awake() {
if (instance != null)
{
Destroy(gameObject);
return;
}
instance = this;
DontDestroyOnLoad(this);
}
void Set_Jwt(string _jwt)
{
Jwt = _jwt;
Jwt_data = decode_jwt(_jwt);
playerUsername = (string)Jwt_data["username"];
Debug.Log("Jwt set");
Debug.LogWarning(playerUsername);
}
private JObject decode_jwt(string _jwt)
{
string[] splitted = _jwt.Split('.');
var part = splitted[1];
// Code only runs until here
byte[] _dec = Convert.FromBase64String(part);
string decodedjwt = Encoding.UTF8.GetString(_dec);
return JObject.Parse(decodedjwt);
}
public void LogIn(string _jwt) {
Debug.LogWarning("LogIn called");
Set_Jwt(_jwt);
isLoggedIn = true;
Debug.Log("Trying to load " + loggedInSceneName);
SceneManager.LoadScene(loggedInSceneName);
}
編集:私は新しいC#のConsoleApplicationほぼ同じコードを書かれている、そしてそれはにSystem.FormatExceptionをスロー
: "無効な長さのbase64文字配列"
static void Main(string[] args)
{
string jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJncy5hd2Vzb21lc3R1ZmYuYXQiLCJpYXQiOjE1MTA1OTkyNzQsImV4cCI6MTUxMDYwMjg3MywidWlkIjoiMTY1ZWMxZjAtYzhhNC0xMWU3LTk2ZWQtYzNjNGQ4NTRmM2I4IiwiYXV0aCI6dHJ1ZSwidXNlcm5hbWUiOiJnYWJlbml6aGVyZSIsImlwIjoiMTk0LjIwOC4xMzguMTI4IiwianRpIjoiNjg4NWM0N2YtMjk3NS00N2MyLTgzYTktN2RmMjhmODE3NDljIn0.tRhx3mUbGBxoGFFr0t6dnPMrdlUT4UKJKLBY_9IiJdBePWp1S10Z91875z6OFK92ymACRR_wO3_1_h6fKXAPTQ";
string[] splitted = jwt.Split('.');
var part = splitted[1];
byte[] arr = Convert.FromBase64String(part);
string res = Encoding.UTF8.GetString(arr);
Console.WriteLine(res);
Console.Read();
}
今すぐどうすればよいですか?
これにより、より多くのコードが実行されるのを防ぐ方法を教えてください。例外?クラッシュ? – AlG
名前をつけるのが大事ですが、私は本当にこのクラスがいくつかの人によって書かれたことを願っていますが、命名は非常に矛盾しているので、標準に従うと非常に便利です1 /単語を連結するときに_一貫性がある(例:SetJwt)。 2 /変数名: '_'は通常、プライベートフィールド(引数でもローカル変数でもない)を表します。 3 /メソッド用にパスカル・ケーシングを使用する(例:decode_jwtとDecodeJwt)。その他の提案は、[C#コーディング規則](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/coding-conventions)を参照してください。 – Icepickle
@AlG no nothing 。 Debug.Log()を行の前後に置くと、前の行だけが表示されます。本当に、何もありません。 – DatNoHand