0

我需要在 Winforms 应用程序中集成 Google Indexing API,但在 MVC Web 应用程序中成功运行的相同代码在 Winforms 上失败,一段时间后抛出 TaskCanceledException。

我将代码减少到最低限度,这是在 MVC 控制器中工作的代码:

public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
        try
        {
            var path = "C:\\delme\\pimpi-339712-a3a8fa51f993.json"; // the private key of my service account owner of the site
            GoogleCredential googleCredential;
            using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                googleCredential = GoogleCredential.FromStream(stream).CreateScoped(new[] { "https://www.googleapis.com/auth/indexing" });
            }

            var credential = googleCredential.UnderlyingCredential;
            var googleIndexingApiClientService = new IndexingService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential
            });

            string url = "https://www.pimpmytrip.it/cosa-vedere-madrid-in-3-giorni/";
            var metaDataRequest = new GetMetadataRequest(googleIndexingApiClientService, url);

            var meta = await metaDataRequest.ExecuteAsync();
        }
        catch (Exception ex)
        {
        }
    }
}

如果在 Winforms 事件处理程序中使用相同的代码,则它不起作用:

private async void btnVerify_Click(object sender, EventArgs e)
{
    try
    {
        var path = "C:\\delme\\pimpi-339712-a3a8fa51f993.json"; // the private key of my service account owner of the site
        GoogleCredential googleCredential;
        using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            googleCredential = GoogleCredential.FromStream(stream).CreateScoped(new[] { "https://www.googleapis.com/auth/indexing" });
        }

        var credential = googleCredential.UnderlyingCredential;
        var googleIndexingApiClientService = new IndexingService(new BaseClientService.Initializer
        {
            HttpClientInitializer = credential
        });

        string url = "https://www.pimpmytrip.it/cosa-vedere-madrid-in-3-giorni/";
        var metaDataRequest = new GetMetadataRequest(googleIndexingApiClientService, url);

        var meta = await metaDataRequest.ExecuteAsync(); // throws TaskCanceledException
    }
    catch (Exception ex)
    {
    }
}

我错过了什么?如果我在 MVC 应用程序中而不是在 Winforms 应用程序中使用它,为什么它可以工作?

4

0 回答 0