首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >3层ASP.NET应用程序-需要批评/建议

3层ASP.NET应用程序-需要批评/建议
EN

Code Review用户
提问于 2011-07-06 17:58:42
回答 3查看 1.4K关注 0票数 7

我现在的设置是一个3层应用程序: UI > BLL > DAL。每个层都被设置为一个单独的项目。UI是一个ASP.Net网站,BLL & DAL是类库项目。

我已经展示了来自我的每个层的一些示例代码。希望你们能批评我的应用程序设计,给我一些提示/指点,否则我做错了,引导我朝着正确的方向前进。谢谢!

DAL法

代码语言:javascript
复制
public static object Get_UserId(string username)
{
    ConnectionSettings connectionSettings = new ConnectionSettings();
    SqlConnection sqlConnection = new SqlConnection(connectionSettings.ConnectionString);
    string sql = String.Format("select UserId from Users where Username = '{0}'", username);
    try
    {
        sqlConnection.Open();
        SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
        return sqlCommand.ExecuteScalar();
    }
    catch
    {                
        throw new DALException("Unable to retreive User ID");
    }
    finally
    {
        sqlConnection.Close();
    }
}

负责提取用户ID

的BLL方法

代码语言:javascript
复制
 public static int GetUserId(string username)
 {
     try
     {
         int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());
         return userId;
     }
     catch (Exception ex)
     {
         throw new BLLException(ex.Message);
     }
 }

从UI:

调用BLL:

代码语言:javascript
复制
try
{
    int id = UserBLL.GetUserId("bobloblaw");
    Response.Write(id);
}
catch (DALException dalEx)
{
    Response.Write(dalEx.Message);
}
catch (BLLException bllEx)
{
    Response.Write(bllEx.Message);
}
EN

回答 3

Code Review用户

发布于 2011-07-07 05:24:33

我将在您的代码/方法中更改的内容:

  • 日志错误
  • 摆脱静态服务方法
  • 在ui中隐藏dll异常。在BLL中捕获它并记录它/用它做一些事情。
  • 将DLL更改为BLL中的方法,而不是:

int userId = Int32.Parse(UserDAL.Get_UserId(username).ToString());

将使用:

int userId = new UserDAL().Get_UserId(username);

这些都是我脑子里最先想到的事情。

票数 2
EN

Code Review用户

发布于 2011-08-06 03:16:30

我会第二次摆脱静态方法。我认为,数据访问应该是基于实例的。

但是,我的主要抓地力是,您没有使用参数化查询。此代码:

代码语言:javascript
复制
string sql = String.Format("select UserId from Users where Username = '{0}'", username);

应:

代码语言:javascript
复制
string sql = @"select UserId from Users where Username = @username");
SqlCommand sqlCommand = new SqlCommand(sql, sqlConnection);
sqlCommand.Parameters.AddWithValue("@username", username);

这样做将缓解使用string.Format(...)的SQL注入问题。我习惯于始终使用参数化查询,不管数据输入是否传递数据。没有理由不这样做。

另外,与使用finally不同,使用using语句来关闭和释放SqlCommandSqlConnection之类的数据对象。

票数 2
EN

Code Review用户

发布于 2011-08-06 08:18:35

  1. 我同意IAmDeveloper的观点,BLL方法应该是: int userId =新的UserDAL().Get_UserId(用户名);
  2. 我同意蒂姆·米尔斯的观点,您应该使用参数化查询。
  3. 我将更改异常处理的整个方法:
    • 捕获DAL.Get_UserId中的所有异常并将它们替换为DALException是错误的。这样做,您将丢失有关原始异常的所有信息,例如堆栈跟踪,并且只保留消息(有时消息本身可能非常无用)。相反,创建更改BLLException构造函数以接受内部异常:公共BLLException (字符串消息,异常内部):base (消息,内部){}并相应抛出它:抛出新的BLLException (“错误获取用户ID",ex);然后可以通过InnerException属性访问内部异常。
    • 您正在尝试在UI层捕获DALException,但它永远不会发生,因为业务层已经用BLLExceptions替换了它们。
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/3312

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档