我关注this指南,直到我必须从网址获取访问令牌的最后一步。但它附加在#字符后面,我不知道如何获取URL的那一部分。有人请告诉我一个有效的代码,或者可能采用不同的方法来获取这些信息。
答案 0 :(得分:2)
您需要fragment。
var fragment = new Uri("http://www.example.com/test#myfragment").Fragment;
Console.WriteLine(fragment);
Console.WriteLine(!string.IsNullOrEmpty(fragment) ? fragment.SubString(1) : string.Empty);
然后你可以提取访问令牌:
&
=
-
var fragment = new Uri("https://www.example.com/cb#access_token=bHLgV4q6--&token_type=bearer&xoauth_yahoo_guid=JTDI2OCE&state=XYZ").Fragment;
if (string.IsNullOrEmpty(fragment))
{
throw new Exception("Access token not found.");
}
fragment = fragment.Substring(1);
var accessToken = fragment.Split(new[] { "&" }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('='))
.FirstOrDefault(p => p.Length == 2 && p[0] == "access_token")?[1]
?? throw new Exception("Access token not found");
答案 1 :(得分:0)
以下程序使用Regex,我们有输入和输出,使用C#中的Url Fragments。
using System;
namespace Solutions
{
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
const string RedirectUrl = "https://www.example.com/cb#access_token=bHLgV4q6--&token_type=bearer&xoauth_yahoo_guid=JTDI2OCE&state=XYZ";
// Create Uri
var uriAddress = new Uri(RedirectUrl);
if (string.IsNullOrEmpty(uriAddress.Fragment))
{
Console.WriteLine("Null Fragment");
return;
}
Console.WriteLine(uriAddress.Fragment);
// To get complete appended Access code
Console.WriteLine(uriAddress.Fragment.Substring(uriAddress.Fragment.IndexOf("#", StringComparison.CurrentCultureIgnoreCase)));
// Apply Regex to get matches
var regex = new Regex("([^?=&]+)(=([^&]*))?");
var matches = regex.Matches(uriAddress.Fragment);
foreach (Match match in matches)
{
var keyValueSplit = match.Value.Split(new[] { '=' }, 2, StringSplitOptions.None);
Console.WriteLine(keyValueSplit[0] + " = " + keyValueSplit[1]);
}
Console.ReadLine();
}
}
}
输出
#=的access_token bHLgV4q6 - &安培; token_type =承载&安培; xoauth_yahoo_guid = JTDI2OCE&安培;状态= XYZ
#=的access_token bHLgV4q6 - &安培; token_type =承载&安培; xoauth_yahoo_guid = JTDI2OCE&安培;状态= XYZ
#access_token = bHLgV4q6 -
token_type = bearer
xoauth_yahoo_guid = JTDI2OCE
州= XYZ