Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 访问令牌已过期,无法刷新。错误:刷新错误,刷新错误,刷新错误_C#_Asp.net Mvc_Google Api_Google Oauth - Fatal编程技术网

C# 访问令牌已过期,无法刷新。错误:刷新错误,刷新错误,刷新错误

C# 访问令牌已过期,无法刷新。错误:刷新错误,刷新错误,刷新错误,c#,asp.net-mvc,google-api,google-oauth,C#,Asp.net Mvc,Google Api,Google Oauth,我正在将google日历api集成到aps.net mvc应用程序中。 我收到错误“访问令牌已过期,无法刷新。错误:刷新错误、刷新错误、刷新错误”。 在本地主机上运行时,代码可以正常工作,但在服务器上运行时,出现上述错误 代码是 public async Task< ActionResult> Index() { var userId = User.Identity.GetUserId(); var _User = "

我正在将google日历api集成到aps.net mvc应用程序中。 我收到错误“访问令牌已过期,无法刷新。错误:刷新错误、刷新错误、刷新错误”。 在本地主机上运行时,代码可以正常工作,但在服务器上运行时,出现上述错误 代码是

public async Task< ActionResult> Index()
    {
            var userId = User.Identity.GetUserId();
            var _User = "Usr" + userId;
            string credPath = Server.MapPath($"~/UsersToken/{_User}");
            UserCredential UsrCred = null;
            FileDataStore fileStore = new FileDataStore(credPath);
            TokenResponse tokenResponse = await fileStore.GetAsync<TokenResponse>(userId);

            if (!Directory.Exists(credPath))
            {
                Directory.CreateDirectory(credPath);
            }
            DirectoryInfo info = new DirectoryInfo(credPath);
            DirectorySecurity security = info.GetAccessControl();
            security.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
            info.SetAccessControl(security);

            if (tokenResponse == null)
            {
                var result = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(CancellationToken.None);
                if (result.Result.Credential == null) // <<- it's always true, so it always gets redirected
                    return Redirect(result.Result.RedirectUri);
                else
                {
                    UsrCred = result.Result.Credential;
                }
            }
            else
            {
                IAuthorizationCodeFlow flow =
                    new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
                    {
                        ClientSecrets = new ClientSecrets
                        {
                            ClientId = _clientId,
                            ClientSecret = _clientSecret
                        },
                        Scopes = Scopes,
                        DataStore = new FileDataStore(credPath, true)
                    //DataStore = new FileDataStore(Google.Apis.Auth)
                });
                UsrCred = new UserCredential(flow, userId, tokenResponse);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = UsrCred,
                ApplicationName = ApplicationName,
            });
            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin = DateTime.Now;
            request.ShowDeleted = false;
            request.SingleEvents = true;
            request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
            Events events = request.Execute();

            List<EventModel> Result = new List<EventModel>();
            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    Result.Add(
                        new EventModel()
                        {
                            Sumarry = eventItem.Summary,
                            Description = eventItem.Description,
                            StartDate = eventItem.Start.DateTime,
                            EndDate = eventItem.End.DateTime,
                            GoogleMeetLink = eventItem.HangoutLink
                        }
                     );
                }
            }
            else
            {
                //Console.WriteLine("No upcoming events found.");
            }

            return View(Result);
    }
公共异步任务索引()
{
var userId=User.Identity.GetUserId();
var\u User=“Usr”+用户ID;
字符串credPath=Server.MapPath($“~/UsersToken/{u User}”);
UserCredential UsrCred=null;
filedatastorefilestore=新的FileDataStore(credPath);
TokenResponse TokenResponse=wait fileStore.GetAsync(userId);
如果(!Directory.Exists(credPath))
{
CreateDirectory(credPath);
}
DirectoryInfo=newdirectoryinfo(credPath);
DirectorySecurity=info.GetAccessControl();
AddAccessRule(新的FileSystemAccessRule(“用户”、FileSystemRights.FullControl、AccessControlType.Allow));
信息.设置访问控制(安全);
if(tokenResponse==null)
{
var result=new AuthorizationCodeMvcApp(这是新的AppFlowMetadata()).authorizationAsync(CancellationToken.None);

if(result.result.Credential==null)//哪个行号在服务器上给出errorerror occour而不是localSystem.InvalidOperationException:访问令牌已过期且无法刷新。错误:刷新错误、刷新错误、刷新错误
public async Task<ActionResult> IndexAsyc(string state, string code, string scope)
    {
        string Lang = ViewBag.Lang ?? "ar";
        string RedirectURL = HttpContext.Request.Url.GetLeftPart(UriPartial.Authority) + $"/{Lang}/Meetings/IndexAsyc";
        var userId = User.Identity.GetUserId();
        var _User = "Usr" + userId;
        string credPath = Server.MapPath($"~/UsersToken/{_User}");
        UserCredential UsrCred = null;

        FileDataStore fileStore = new FileDataStore(credPath);
        TokenResponse tokenResponse = await fileStore.GetAsync<TokenResponse>(userId);
        // create authorization code flow with clientSecrets
        GoogleAuthorizationCodeFlow authorizationCodeFlow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            DataStore = new FileDataStore(credPath),
            ClientSecrets = new ClientSecrets()
            {
                ClientId = _clientId,
                ClientSecret = _clientSecret
            },
            Scopes = Scopes
        });
        //var result = new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).AuthorizeAsync(CancellationToken.None);

        if (tokenResponse == null)
        {
            // token data does not exist for this user
            tokenResponse = await authorizationCodeFlow.ExchangeCodeForTokenAsync(
              userId, // user for tracking the userId on our backend system
              code,
              RedirectURL, // redirect_uri can not be empty. Must be one of the redirects url listed in your project in the api console
              CancellationToken.None);
        }
        TokenResponse tokenResponse2 = await fileStore.GetAsync<TokenResponse>(userId);

        if (tokenResponse2 != null)
        {
            return RedirectToAction("Index");
        }

        var Creds = new UserCredential(authorizationCodeFlow, userId, tokenResponse2);
        if (Creds != null) // result.Credential != null )
        {
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = Creds,//result.Credential,
                ApplicationName = ApplicationName,
            });


            return RedirectToAction("Index");
        }
        else
        {
            return new RedirectResult(RedirectURL);
        }
    }