从页面访问静态类代码是否安全/线程安全?

时间:2020-03-09 13:00:05

标签: c# asp.net webforms thread-safety

我很欣赏这种类型的问题,但是我阅读的内容越多,我就越困惑,因此,您将对是/否答案以及基于以下代码的解释表示赞赏。我已经测试了代码并且可以工作,但是我寻求一点共同的智慧,因为我无法模拟同时访问请求。

在我的Web应用程序中,数据库具有来自多个组织的用户帐户。该代码的目标是检索特定于其各自组织的某些访问凭据,然后使用使用这些凭据创建的对象与第三者系统集成。

下面是否有可能,如果多个人同时点击该用户,则该用户可能会接触到另一个组织的凭据,尤其是:

  1. 访问静态代码时页面的线程安全性是否受到损害?
  2. 在我的示例中使用静态代码时,静态代码能否将值返回到错误的线程?

应用范围内的类逻辑

public static class ThirdParty
{

    public class ThirdPartyCredentials
    {
        public string AppId { get; set; }
        public string AppSecret { get; set; }
    }

    // Retrieves the third-party system credentials for the current user's organisation
    public static ThirdPartyCredentials GetThirdPartyCloudCredentials()
    {
        ThirdPartyCredentials cc = new ThirdPartyCredentials();

        // This usually happens in business logic, but example shown here to illustrate UserId/OrganisationId come from user-based OWIN/Katana cookies
        var user = HttpContext.Current.Request.GetOwinContext().Authentication.User;
        var sqlCommand = new SqlCommand();
        sqlCommand.Parameters.Add("@UserId", SqlDbType.Int, Convert.ToInt32(user.FindFirst("UserId").Value));
        sqlCommand.Parameters.Add("@OrganisationId", SqlDbType.Int, Convert.ToInt32(user.FindFirst("OrganisationId").Value));
        // Code removed from brevity, but returns a DataTable object containing the credentials
        using (DataTable dt = ....)
        {
            cc.AppId = dt.Rows[0]["ThirdPartyAppId"].ToString();
            cc.AppSecret = dt.Rows[0]["ThirdPartyAppSecret"].ToString();
            return cc;
        }
    }

    public static ApiClient GetApiClient()
    {
        var creds = GetThirdPartyCloudCredentials();

        return new ApiClient()
        {
            Username = creds.AppId,
            Password = creds.AppSecret
        };
    }
}

页面逻辑

    protected void Page_Load(object sender, EventArgs e)
    {
        var apiClient = GetApiClient();
        var dataApi = new ThirdPartySystem.DataApi() {
            ApiClient = apiClient;
        };

        foreach (var c in dataApi.GetData().ObjectCollection)
        {
            MyDropDownList.Items.Add(new ListItem(c.Title, c.Id));
        }

    }

0 个答案:

没有答案