Using gmail api with asp.net web api

本文关键字:api net web asp with gmail Using | 更新日期: 2023-09-27 18:17:22

我想在asp.net web API项目中使用gmail API。这是我目前所看到的:

        UserCredential credential;
        var cleantSecretPath = HostingEnvironment.MapPath("~/client_secret.json");
        var rootPath = HostingEnvironment.MapPath("~/");
        if (rootPath != null)
        {
            var credentialPath = Path.Combine(rootPath, "Credentials");
            var directoryInfo = Directory.CreateDirectory(credentialPath);
        }
        var credentialsPath = HostingEnvironment.MapPath("~/Credentials/");
        using (var stream = new FileStream(cleantSecretPath, FileMode.Open, FileAccess.Read))
        {
            var secret = GoogleClientSecrets.Load(stream).Secrets;
            var dataStore = new FileDataStore("test");
            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secret, Scopes, _credentials.Email, CancellationToken.None, dataStore).Result;
        }
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = ApplicationName,
        });
        return

它在本地主机上工作,但一旦我将它部署到azure,我收到一个错误:

<Error>
    <Message>An error has occurred.</Message>
    <ExceptionMessage>One or more errors occurred.</ExceptionMessage>
    <ExceptionType>System.AggregateException</ExceptionType>
    <StackTrace>
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task`1.get_Result() at BL.GmailServiceBl.GetGmailService() in D:'Development'DotNetProjects'GmailAnalysis'BL'GmailServiceBl.cs:line 53 at BL.AnalysisService..ctor(PersonCredentials credentials) in D:'Development'DotNetProjects'GmailAnalysis'BL'AnalysisService.cs:line 22 at WebAPI.Controllers.ValuesController.Get(PersonCredentials credentials) in D:'Development'DotNetProjects'GmailAnalysis'WebAPI'Controllers'ValuesController.cs:line 63 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
    </StackTrace>
    <InnerException>
        <Message>An error has occurred.</Message>
        <ExceptionMessage>Access is denied</ExceptionMessage>
        <ExceptionType>System.Net.HttpListenerException</ExceptionType>
        <StackTrace>
        at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task) at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.<AuthorizeAsync>d__1.MoveNext() in c:'code'github'google-api-dotnet-client'Tools'Google.Apis.Release'bin'Release'1.9.2'default'Src'GoogleApis.Auth.DotNet4'OAuth2'GoogleWebAuthorizationBroker.cs:line 59
        </StackTrace>
    </InnerException>
</Error>

我正在使用client_secret。json用于Web应用程序。谁能给我举个例子或者给我指指方向?

Using gmail api with asp.net web api

下面是一个有效的例子:

var filePath = HostingEnvironment.MapPath("~/build-info.json");
var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
string fileContent;
using (var reader = new StreamReader(fileStream))
{
    fileContent = reader.ReadToEnd();
}

我已经在本地运行并部署到Azure WebApp,它在两个位置都可以工作。

所以像下面这样的东西应该可以工作:

UserCredential credential;
var filePath = HostingEnvironment.MapPath("~/client_secret.json");
using (var stream = new FileStream(filePath , FileMode.Open, FileAccess.Read))
{
    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
        new[] { GmailService.Scope.GmailReadonly },
        "user", CancellationToken.None);
}

在处理了几天类似的问题后,我发现这不是你应该怎么做的:

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secret, Scopes, _credentials.Email, CancellationToken.None, dataStore).Result;

相反,应该使用FlowMetadata方法进行身份验证,如下所示。