谷歌分析与Web应用程序错误

时间:2014-04-22 10:21:37

标签: google-analytics-api

private static readonly IAuthorizationCodeFlow flow =
        new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
        {
            ClientSecrets = new ClientSecrets
            {
                ClientId = "XXXXXXXXX",
                ClientSecret = "XXXXXXXXXXXX"
            },
            Scopes = new[] { AnalyticsService.Scope.AnalyticsReadonly, AnalyticsService.Scope.AnalyticsEdit },
            DataStore = new FileDataStore("Analytics.Auth.Store")//new FileDataStore("Drive.Api.Auth.Store")
        });

我正在使用Google控制台网络应用程序(Google Analytic)的上述代码,但它会出现错误System.UnauthorizedAccessException:拒绝访问“Analytics.Auth.Store”路径。

2 个答案:

答案 0 :(得分:1)

FileDataStore将数据存储在pc上的%AppData%中。您需要确保您可以访问它。

如果您计划从网络服务器运行此功能,则不应使用FileDataStore。您应该创建自己的iDataStore实现,这将使您能够将刷新令牌存储在数据库中。

示例:

 /// 
/// Saved data store that implements . 
/// This Saved data store stores a StoredResponse object.
/// 
class SavedDataStore : IDataStore
{
    public StoredResponse _storedResponse { get; set; }
    /// 
    /// Constructs Load previously saved StoredResponse.
    /// 
    ///Stored response
    public SavedDataStore(StoredResponse pResponse)
    {
        this._storedResponse = pResponse;
    }
    public SavedDataStore()
    {
        this._storedResponse = new StoredResponse();
    }
    /// 
    /// Stores the given value. into storedResponse
    /// .
    /// 
    ///The type to store in the data store
    ///The key
    ///The value to store in the data store
    public Task StoreAsync(string key, T value)
    {
        var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
        JObject jObject = JObject.Parse(serialized);
        // storing access token
        var test = jObject.SelectToken("access_token");
        if (test != null)
        {
            this._storedResponse.access_token = (string)test;
        }
        // storing token type
        test = jObject.SelectToken("token_type");
        if (test != null)
        {
            this._storedResponse.token_type = (string)test;
        }
        test = jObject.SelectToken("expires_in");
        if (test != null)
        {
            this._storedResponse.expires_in = (long?)test;
        }
        test = jObject.SelectToken("refresh_token");
        if (test != null)
        {
            this._storedResponse.refresh_token = (string)test;
        }
        test = jObject.SelectToken("Issued");
        if (test != null)
        {
            this._storedResponse.Issued = (string)test;
        }
        return TaskEx.Delay(0);
    }

    /// 
    /// Deletes StoredResponse.
    /// 
    ///The key to delete from the data store
    public Task DeleteAsync(string key)
    {
        this._storedResponse = new StoredResponse();
        return TaskEx.Delay(0);
    }

    /// 
    /// Returns the stored value for_storedResponse      
    ///The type to retrieve
    ///The key to retrieve from the data store
    /// The stored object
    public Task GetAsync(string key)
    {
        TaskCompletionSource tcs = new TaskCompletionSource();
        try
        {
            string JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(this._storedResponse);
            tcs.SetResult(Google.Apis.Json.NewtonsoftJsonSerializer.Instance.Deserialize(JsonData));
        }
        catch (Exception ex)
        {
            tcs.SetException(ex);
        }
        return tcs.Task;
    }

    /// 
    /// Clears all values in the data store. 
    /// 
    public Task ClearAsync()
    {
        this._storedResponse = new StoredResponse();
        return TaskEx.Delay(0);
    }

    ///// Creates a unique stored key based on the key and the class type.
    /////The object key
    /////The type to store or retrieve
    //public static string GenerateStoredKey(string key, Type t)
    //{
    //    return string.Format("{0}-{1}", t.FullName, key);
    //}
}

然后使用新的SavedDataStore

而不是使用FileDataStore
//Now we load our saved refreshToken.
StoredResponse myStoredResponse = new StoredResponse(tbRefreshToken.Text);
// Now we pass a SavedDatastore with our StoredResponse.

credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
          new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
          new[] { AnalyticsService.Scope.AnalyticsReadonly},
          "user",
          CancellationToken.None,
           new SavedDataStore(myStoredResponse)).Result; }

答案 1 :(得分:1)

这是因为您对Web服务器上的 AppData 文件夹没有写入权限,而 FileDataStore 默认使用该文件夹。

您可以通过提供完整路径作为参数

来使用其他文件夹
FileDataStore(string folder, bool fullPath = false)

示例实施

static FileDataStore GetFileDataStore()
{
    var path = HttpContext.Current.Server.MapPath("~/App_Data/Drive.Api.Auth.Store");
    var store = new FileDataStore(path, fullPath: true);
    return store;
}

这样 FileDataStore 使用应用程序的 App_Data 文件夹来编写TokenResponse。别忘了给Webserver上的App_Data文件夹提供写访问权

您可以在herehere

了解详情