简体   繁体   English

在 ASP.Net web 应用程序数据层中实现 Static 方法是否安全?

[英]Is it safe to implement Static method in ASP.Net web application Datalayer?

I am working on an web application, which is a B2B portal App.我正在开发一个 web 应用程序,它是一个 B2B 门户应用程序。 I am following 2 tier architecture for my app.我正在为我的应用程序遵循 2 层架构。 Below is a piece of code that registers a company to my website下面是一段将公司注册到我的网站的代码

/// <summary>
        /// Register Company with the business bazaar
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        public static bool RegisterCompany(Registration registration)
        {
            bool result;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_RegisterCompany";
                var success = new SqlParameter("@Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
                                               "Result", DataRowVersion.Default, 0);
                var parameters = new[]
                                     {
                                         new SqlParameter("@Name",registration.RegisteredUser.Name),
                                        new SqlParameter("@Designation",registration.Designation ),
                                        new SqlParameter("@Email",registration.RegisteredUser.Email ),
                                        new SqlParameter("@AltEmail",registration.RegisteredUser.AlternateEmail ),
                                        new SqlParameter("@City",registration.City ),
                                        new SqlParameter("@State",registration.State ),
                                        new SqlParameter("@Country",registration.Country ), 
                                        new SqlParameter("@Telephone",registration.Telephone ),
                                        new SqlParameter("@Mobile",registration.Mobile ),
                                        new SqlParameter("@CompanyName",registration.CompanyName ),
                                        new SqlParameter("@Website",registration.Website ),
                                        new SqlParameter("@LoginId",registration.RegisteredUser.UserName ),
                                        new SqlParameter("@Password",registration.RegisteredUser.Password ),
                                        success,
                                     };
                helper.ExecuteScalar(_commandText, CommandType.StoredProcedure, parameters);
                result = (bool) success.Value;
            }
            return result;

        }

What I want to say is that i am using Static methods for all my datalayer methods.我想说的是,我对所有数据层方法都使用了 Static 方法。 As I have gone through various articles on the web stating that Static methods has more advantages over Non-Static methods.正如我浏览 web 上的各种文章一样,指出 Static 方法比非静态方法具有更多优势。 So I have designed my code that way.所以我以这种方式设计了我的代码。 But few days ago I came across ab article that says static methods are useful when you design some utilities for your class other wise use Non-Static, as same static objects are avalaible to other users.但是几天前我看到一篇文章说 static 方法在您为 class 设计一些实用程序时很有用So I just want to make clear which approach to follow, static or non static.所以我只想说明要遵循哪种方法,static 或非 static。

I am using class in this format:我以这种格式使用 class :

public sealed class MyClass
{
    private MyClass(){}
    public static DataTable GetUserInfoByUserId(int userId)
    {
       // My datalayer code goes here
    }
}

SO i am cofused if making the above method static, would'nt make the data of user 1 available to user 2 accessing the application simultaneously.所以我很困惑,如果使用上述方法 static,不会让用户 2 同时访问应用程序的用户 1 的数据可用。 Basically, I want to know the flaws of this design.基本上,我想知道这个设计的缺陷。

UPDATED Below is my class, showing my approach更新以下是我的class ,展示了我的方法

#region

using System.Data;
using System.Data.SqlClient;
using System;

#endregion

namespace InnovativeTechnosoft.BusinessBazaar.Core
{
    public sealed class UserData
    {
        private static string _commandText = string.Empty;


        /// <summary>
        /// Takes username and password as input and sets 
        /// the current user in sessionif the user authenticate
        /// successfully
        /// </summary>
        /// <param name="userName">username as string</param>
        /// <param name="password">password as string</param>
        /// <returns>datatable</returns>
        public static DataTable IsAuthenticated(string userName, string password)
        {
            DataTable dtResult;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_AuthenticateUsers";
                var parameters = new[]
                                     {
                                         new SqlParameter("@username", userName),
                                         new SqlParameter("@password", password),
                                     };
                dtResult = helper.ExecuteSelect(_commandText, CommandType.StoredProcedure, parameters);
            }

            return dtResult;
        }

        /// <summary>
        /// Checks for username if it exists or not
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public static bool IsExistingUser(string userName)
        {
            bool result;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_IsExistingUserName";
                var success = new SqlParameter("@Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
                                              "Result", DataRowVersion.Default, 0);
                var parameters = new[]
                                     {
                                         new SqlParameter("@userName", userName),
                                         success,
                                     };
                helper.ExecuteScalar(_commandText, CommandType.StoredProcedure, parameters);
                result = (bool)success.Value;
            }

            return result;
        }

        /// <summary>
        /// Register Company with the business bazaar
        /// </summary>
        /// <param name="registration"></param>
        /// <returns></returns>
        public static bool RegisterCompany(Registration registration)
        {
            bool result;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_RegisterCompany";
                var success = new SqlParameter("@Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
                                               "Result", DataRowVersion.Default, 0);
                var parameters = new[]
                                     {
                                         new SqlParameter("@Name",registration.RegisteredUser.Name),
                                        new SqlParameter("@Designation",registration.Designation ),
                                        new SqlParameter("@Email",registration.RegisteredUser.Email ),
                                        new SqlParameter("@AltEmail",registration.RegisteredUser.AlternateEmail ),
                                        new SqlParameter("@City",registration.City ),
                                        new SqlParameter("@State",registration.State ),
                                        new SqlParameter("@Country",registration.Country ), 
                                        new SqlParameter("@Telephone",registration.Telephone ),
                                        new SqlParameter("@Mobile",registration.Mobile ),
                                        new SqlParameter("@CompanyName",registration.CompanyName ),
                                        new SqlParameter("@Website",registration.Website ),
                                        new SqlParameter("@LoginId",registration.RegisteredUser.UserName ),
                                        new SqlParameter("@Password",registration.RegisteredUser.Password ),
                                        success,
                                     };
                helper.ExecuteScalar(_commandText, CommandType.StoredProcedure, parameters);
                result = (bool) success.Value;
            }
            return result;

        }

        /// <summary>
        /// Recovers Password 
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool RecoverPassword(string email, out string password)
        {
            bool result;
            password = string.Empty;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_RecoverPassword";
                var success = new SqlParameter("@Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
                                               "Result", DataRowVersion.Default, 0);
                var pwd = new SqlParameter("@Password", SqlDbType.NVarChar, 50, ParameterDirection.Output, true, 0, 0, "Password", DataRowVersion.Default, string.Empty);
                var parameters = new[]
                                     {
                                        new SqlParameter("@Email",email ),
                                        success,
                                     };
                helper.ExecuteScalar(_commandText, CommandType.StoredProcedure, parameters);
                result = (bool)success.Value;
                password = Convert.ToString(pwd.Value);
            }
            return result;
        }
        /// <summary>
        /// Update  Password 
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool UpdatePassword(int userId,string password)
        {
            bool result;
            using (var helper = new DbHelper())
            {
                _commandText = "sp_UpdatePassword";
                var success = new SqlParameter("@Success", SqlDbType.Bit, 1, ParameterDirection.Output, true, 0, 0,
                                               "Result", DataRowVersion.Default, 0);
                var parameters = new[]
                                     {
                                         new SqlParameter ("@UserId",userId),
                                        new SqlParameter("@Password",password ),
                                        success,
                                     };
                helper.ExecuteScalar(_commandText, CommandType.StoredProcedure, parameters);
                result = (bool)success.Value;
            }
            return result;
        }

    }
}

It would be a great help.这将是一个很大的帮助。

Regards Amit Ranjan问候阿米特·兰詹

You can uses static functions, but you should avoid static variables or members at all.您可以使用 static 函数,但您应该完全避免 static 变量或成员。 In short, don't "save" any information in static context.简而言之,不要在 static 上下文中“保存”任何信息。 These are available in application scope and that may be the same for different requests from different users.这些在应用程序 scope 中可用,并且对于来自不同用户的不同请求可能相同。

Running data access operations in static functions should be no problem.在 static 函数中运行数据访问操作应该没有问题。

Making your methods instance instead of static might help you with maintenance down the road.使您的方法实例而不是 static 可能会帮助您进行后续维护。 For example, perhaps you'll want to be able to substitute a different implementation of your DBHelper class in some cases.例如,在某些情况下,您可能希望能够替换 DBHelper class 的不同实现。

Right now, since your static method calls var helper = new DbHelper() , you are locked into using that instance.现在,由于您的 static 方法调用var helper = new DbHelper() ,因此您被锁定使用该实例。 However, let's say you want to write some unit tests that use a different DbHelper class that connects to a different database.但是,假设您要编写一些单元测试,这些单元测试使用连接到不同数据库的不同 DbHelper class。 You'd be better off with a class like:您最好使用 class ,例如:

    public class DataLayer {
        public DataLayer(IDbHelper dbHelper){
            this.DbHelper = dbHelper;
        }
        public IDbHelper DbHelper { get; private set; }

        public void RunQuery(){
            // Do stuff with dbhelper
        }
    }

Now you can pass in a different DbHelper in different circumstances.现在您可以在不同的情况下传入不同的 DbHelper。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在ASP.NET Core上实现“Fire and Forget”方法的安全方法 - Safe way to implement a “Fire and Forget” method on ASP.NET Core 在 asp.net 上创建 static 文件是否安全? - Is it safe to create a static file on asp.net? 如何为现有的ASP.NET Web应用程序实现页面计数器 - How to implement page counter for an existing ASP.NET web application 如何为ASP.NET Web应用程序实现事件记录器? - How to implement event logger for ASP.NET web application? 在 asp.net web 应用程序中使用静态字典 - Use static dictionary in asp.net web application ASP.NET Web 窗体应用程序的静态文件浏览器缓存 - Static File Browser Caching for ASP.NET Web Forms Application 在ASP.NET Web Api中实现对Restangulars .several()方法的支持 - Implement support for Restangulars .several() method in ASP.NET Web Api ASP.net中的静态方法 - Static Method in ASP.net 在 ASP.NET web 应用程序中,我在哪种方法中实现一个每 5 分钟调用一次 function 的计时器? 没有 main() 可以在 PageLoad 中吗? - In ASP.NET web application, in which method do I implement a timer that calls a function every 5 minutes? There's no main() could it be in PageLoad? 如何在asp.net web应用程序中调用javascript方法 - How to call javascript method in asp.net web application
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM