Nhibenate - DOS 攻击

发布于 2024-12-07 23:02:35 字数 15138 浏览 0 评论 0原文

我公司的一位测试人员在我的 ASP.Net MVC 3 解决方案中发现了一个错误,我认为这很常见。

向它可以处理的服务器发送一封邮件。但是,如果您发送大量帖子,例如拒绝服务攻击(DoS 攻击),它会引发异常:

Server Error in '/' Application.
Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: NHibernate.LazyInitializationException: Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed

Source Error:

Line 880:
Line 881:
Line 882:            return
Line 883:                Json(
Line 884:                    new


Source File: C:\Projects\DavidPM\Hosts\ProdMaster.Hosts.Web\Areas\Sales\Controllers\CustomerOrderController.cs    Line: 882

Stack Trace:

[LazyInitializationException: Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed]
   NHibernate.Collection.AbstractPersistentCollection.ThrowLazyInitializationException(String message) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:484
   NHibernate.Collection.AbstractPersistentCollection.ThrowLazyInitializationExceptionIfNotConnected() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:474
   NHibernate.Collection.AbstractPersistentCollection.Initialize(Boolean writing) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:465
   NHibernate.Collection.AbstractPersistentCollection.Read() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:264
   NHibernate.Collection.Generic.PersistentGenericBag`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\Generic\PersistentGenericBag.cs:142
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +63
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +78
   UseSoft.ProdMaster.Hosts.Web.Areas.Sales.Controllers.CustomerOrderController.SaveOrUpdateOrderLines(CustomerOrderModel customerOrderModel) in C:\Projects\DavidPM\Hosts\ProdMaster.Hosts.Web\Areas\Sales\Controllers\CustomerOrderController.cs:882
   lambda_method(Closure , ControllerBase , Object[] ) +162
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

如下所述:

多次单击按钮。或者点击一次并回车,就会向服务器“Post”发送大量请求。

模型基本上是:

public class CustomerOrderModel
{
    public CustomerOrderModel()
    {
        this.CustomerOrderLines = new List<CustomerOrderLineModel>();
        this.CustomerOrderHeader = new CustomerOrderHeaderModel();
    }

    public CustomerOrderHeaderModel CustomerOrderHeader
    { get; set; }

    public List<CustomerOrderLineModel> CustomerOrderLines
    { get; set; }

}

控制器:

[HttpPost]
        public JsonResult SaveOrUpdateOrderLines(  CustomerOrderModel customerOrderModel)
        {

  if (customerOrderModel.CustomerOrderHeader.OrderNumber == 0)
             {
                 customerOrderModel.CustomerOrderHeader.OrderNumber = this.CustomerOrderService.CreateOrUpdate(customerOrderHeader, false);
             }

返回 杰森( 新的 { 订单编号 = customerOrderModel.CustomerOrderHeader.OrderNumber, 客户订单行 = 新 { 客户订单行 = ( 来自 custOrderHeader.CustomerOrderLines 中的订单行 选择新的 { Id = 订单.Id, 行号 = orderline.行号, LineStatus = orderline.LineStatus CustomerOrder

                            ).ToArray()

                        }
                }, 
                JsonRequestBehavior.AllowGet
            );

}

服务:

 public class CustomerOrderService : ServiceBase, ICustomerOrderService
    {

 public long CreateOrUpdate(CustomerOrderHeader customerOrderHeader, bool updateCustomerOrderHeader)
        {
            using (var session = this.SessionManager.OpenSession())
            {
                var transaction = session.BeginTransaction();

                try
                {
                    //TODO: CHECKS IF PARTNER EXISTS
                    bool existsPartner = false;
                    long number = 0;
                    if (this.PartnerService.FindByName(customerOrderHeader.Partner.Name) != null)
                    {
                        existsPartner = true;
                    }

                    //CREATE PARTNER AND PARTNER ADDRESSES
                    if (!existsPartner)
                    {
                        this.PartnerService.Create(customerOrderHeader.Partner as Partner);
                    }



                    if (!updateCustomerOrderHeader)
                    {
                        number = this.CustomerOrderHeaderService.Create(customerOrderHeader, true);
                    }
                    else
                    {
                        this.CustomerOrderHeaderService.Create(customerOrderHeader, false);
                    }
                    transaction.Commit();
                    return number;


                }

                catch (Exception ex)
                {

                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    session.Close();
                }
            }
        }



        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerOrderService"/> class.
        /// </summary>
        /// <param name="sessionManager">
        /// The session manager.
        /// </param>
        public CustomerOrderService(ISessionManager sessionManager)
        {
            this.SessionManager = sessionManager;
        }
}

CustomerOrderHeaderService:

public long Create(CustomerOrderHeader customerOrderHeader, bool firstTime)
        {


            using (var session = this.SessionManager.OpenSession())
            {
            //    var transaction = session.BeginTransaction();

            //    try
            //    {




                    if (firstTime)
                    {
                        foreach (var customerOrderLine in customerOrderHeader.CustomerOrderLines)
                        {
                            customerOrderLine.CustomerOrderHeader = customerOrderHeader;
                        }

                        customerOrderHeader.OrderNumber = this.NextOrderNumber();
                        session.Save(customerOrderHeader);
                    }
                    else
                    {

                        CustomerOrderHeader customerOrderHeaderToBeChanged =
                            this.FindByOrderNumber(customerOrderHeader.OrderNumber);

                        customerOrderHeaderToBeChanged.CopyDomainProperties(
                            customerOrderHeader, new[]
                                                     {
                                                         "Id", 
                                                         "Partner", 
                                                         "DataOwner", 
                                                         "dataOwner", 
                                                         "SysCreatedOn",
                                                         "SysCreatedBy",
                                                         "CustomerOrderLines"
                                                     });
                        customerOrderHeaderToBeChanged = UpdateLines(customerOrderHeader, customerOrderHeaderToBeChanged);
                        List<ICustomerOrderLine> linestoBeInserted = GetTheLineNumbersToBeInserted(customerOrderHeader);

                        foreach (var customerOrderLine in linestoBeInserted)
                        {
                            customerOrderHeaderToBeChanged.CustomerOrderLines.Add(customerOrderLine);
                            customerOrderLine.CustomerOrderHeader = customerOrderHeaderToBeChanged;
                        }

                        session.Update(customerOrderHeaderToBeChanged);
                    }

            //        transaction.Commit();
            }
            //    catch (Exception ex)
            //    {
            //        transaction.Rollback();
            //        throw ex;
            //    }
            //    finally
            //    {
            //        session.Close();
            //    }
            //}
            //throw new System.ArgumentException();

            return customerOrderHeader.OrderNumber;
        }


public class CustomerOrderHeaderService : ServiceBase, ICustomerOrderHeaderService
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerOrderHeaderService"/> class.
        /// </summary>
        /// <param name="sessionManager">
        /// The session manager.
        /// </param>
        public CustomerOrderHeaderService(ISessionManager sessionManager)
        {
            this.SessionManager = sessionManager;
        }

        #endregion

 public long Create(CustomerOrderHeader customerOrderHeader, bool firstTime)
        {


            using (var session = this.SessionManager.OpenSession())
            {
            //    var transaction = session.BeginTransaction();

            //    try
            //    {




                    if (firstTime)
                    {
                        foreach (var customerOrderLine in customerOrderHeader.CustomerOrderLines)
                        {
                            customerOrderLine.CustomerOrderHeader = customerOrderHeader;
                        }

                        customerOrderHeader.OrderNumber = this.NextOrderNumber();
                        session.Save(customerOrderHeader);
                    }
                    else
                    {

                        CustomerOrderHeader customerOrderHeaderToBeChanged =
                            this.FindByOrderNumber(customerOrderHeader.OrderNumber);

                        customerOrderHeaderToBeChanged.CopyDomainProperties(
                            customerOrderHeader, new[]
                                                     {
                                                         "Id", 
                                                         "Partner", 
                                                         "DataOwner", 
                                                         "dataOwner", 
                                                         "SysCreatedOn",
                                                         "SysCreatedBy",
                                                         "CustomerOrderLines"
                                                     });
                        customerOrderHeaderToBeChanged = UpdateLines(customerOrderHeader, customerOrderHeaderToBeChanged);
                        List<ICustomerOrderLine> linestoBeInserted = GetTheLineNumbersToBeInserted(customerOrderHeader);

                        foreach (var customerOrderLine in linestoBeInserted)
                        {
                            customerOrderHeaderToBeChanged.CustomerOrderLines.Add(customerOrderLine);
                            customerOrderLine.CustomerOrderHeader = customerOrderHeaderToBeChanged;
                        }

                        session.Update(customerOrderHeaderToBeChanged);
                    }

            //        transaction.Commit();
            }
            //    catch (Exception ex)
            //    {
            //        transaction.Rollback();
            //        throw ex;
            //    }
            //    finally
            //    {
            //        session.Close();
            //    }
            //}
            //throw new System.ArgumentException();

            return customerOrderHeader.OrderNumber;
        }
}

One of the testers in my company found an error on my ASP.Net MVC 3 solution, that I believe is pretty common.

One post to the server it can handle. But if you send a lot of posts, like a denial-of-service attack (DoS attack) it thrown an exception:

Server Error in '/' Application.
Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: NHibernate.LazyInitializationException: Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed

Source Error:

Line 880:
Line 881:
Line 882:            return
Line 883:                Json(
Line 884:                    new


Source File: C:\Projects\DavidPM\Hosts\ProdMaster.Hosts.Web\Areas\Sales\Controllers\CustomerOrderController.cs    Line: 882

Stack Trace:

[LazyInitializationException: Initializing[UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader#567]-failed to lazily initialize a collection of role: UseSoft.ProdMaster.Domain.Entities.CustomerOrderHeader.CustomerOrderLines, no session or session was closed]
   NHibernate.Collection.AbstractPersistentCollection.ThrowLazyInitializationException(String message) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:484
   NHibernate.Collection.AbstractPersistentCollection.ThrowLazyInitializationExceptionIfNotConnected() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:474
   NHibernate.Collection.AbstractPersistentCollection.Initialize(Boolean writing) in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:465
   NHibernate.Collection.AbstractPersistentCollection.Read() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\AbstractPersistentCollection.cs:264
   NHibernate.Collection.Generic.PersistentGenericBag`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() in d:\CSharp\NH\NH\nhibernate\src\NHibernate\Collection\Generic\PersistentGenericBag.cs:142
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +63
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.Enumerable.ToArray(IEnumerable`1 source) +78
   UseSoft.ProdMaster.Hosts.Web.Areas.Sales.Controllers.CustomerOrderController.SaveOrUpdateOrderLines(CustomerOrderModel customerOrderModel) in C:\Projects\DavidPM\Hosts\ProdMaster.Hosts.Web\Areas\Sales\Controllers\CustomerOrderController.cs:882
   lambda_method(Closure , ControllerBase , Object[] ) +162
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
   System.Web.Mvc.Controller.ExecuteCore() +116
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8862381
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

The is described bellow:

Click in a button many times. Or click once and press enter, it will send a lot of requests to the server "Post".

The Model Basically is:

public class CustomerOrderModel
{
    public CustomerOrderModel()
    {
        this.CustomerOrderLines = new List<CustomerOrderLineModel>();
        this.CustomerOrderHeader = new CustomerOrderHeaderModel();
    }

    public CustomerOrderHeaderModel CustomerOrderHeader
    { get; set; }

    public List<CustomerOrderLineModel> CustomerOrderLines
    { get; set; }

}

The Controller:

[HttpPost]
        public JsonResult SaveOrUpdateOrderLines(  CustomerOrderModel customerOrderModel)
        {

  if (customerOrderModel.CustomerOrderHeader.OrderNumber == 0)
             {
                 customerOrderModel.CustomerOrderHeader.OrderNumber = this.CustomerOrderService.CreateOrUpdate(customerOrderHeader, false);
             }

return
Json(
new
{
OrderNumber = customerOrderModel.CustomerOrderHeader.OrderNumber,
CustomerOrderLines = new
{
CustomerOrderLine = (
from ordeline in custOrderHeader.CustomerOrderLines
select new
{
Id = ordeline.Id,
LineNumber = ordeline.LineNumber,
LineStatus = ordeline.LineStatus
}

                            ).ToArray()

                        }
                }, 
                JsonRequestBehavior.AllowGet
            );

}

The CustomerOrder Service:

 public class CustomerOrderService : ServiceBase, ICustomerOrderService
    {

 public long CreateOrUpdate(CustomerOrderHeader customerOrderHeader, bool updateCustomerOrderHeader)
        {
            using (var session = this.SessionManager.OpenSession())
            {
                var transaction = session.BeginTransaction();

                try
                {
                    //TODO: CHECKS IF PARTNER EXISTS
                    bool existsPartner = false;
                    long number = 0;
                    if (this.PartnerService.FindByName(customerOrderHeader.Partner.Name) != null)
                    {
                        existsPartner = true;
                    }

                    //CREATE PARTNER AND PARTNER ADDRESSES
                    if (!existsPartner)
                    {
                        this.PartnerService.Create(customerOrderHeader.Partner as Partner);
                    }



                    if (!updateCustomerOrderHeader)
                    {
                        number = this.CustomerOrderHeaderService.Create(customerOrderHeader, true);
                    }
                    else
                    {
                        this.CustomerOrderHeaderService.Create(customerOrderHeader, false);
                    }
                    transaction.Commit();
                    return number;


                }

                catch (Exception ex)
                {

                    transaction.Rollback();
                    throw ex;
                }
                finally
                {
                    session.Close();
                }
            }
        }



        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerOrderService"/> class.
        /// </summary>
        /// <param name="sessionManager">
        /// The session manager.
        /// </param>
        public CustomerOrderService(ISessionManager sessionManager)
        {
            this.SessionManager = sessionManager;
        }
}

The CustomerOrderHeaderService:

public long Create(CustomerOrderHeader customerOrderHeader, bool firstTime)
        {


            using (var session = this.SessionManager.OpenSession())
            {
            //    var transaction = session.BeginTransaction();

            //    try
            //    {




                    if (firstTime)
                    {
                        foreach (var customerOrderLine in customerOrderHeader.CustomerOrderLines)
                        {
                            customerOrderLine.CustomerOrderHeader = customerOrderHeader;
                        }

                        customerOrderHeader.OrderNumber = this.NextOrderNumber();
                        session.Save(customerOrderHeader);
                    }
                    else
                    {

                        CustomerOrderHeader customerOrderHeaderToBeChanged =
                            this.FindByOrderNumber(customerOrderHeader.OrderNumber);

                        customerOrderHeaderToBeChanged.CopyDomainProperties(
                            customerOrderHeader, new[]
                                                     {
                                                         "Id", 
                                                         "Partner", 
                                                         "DataOwner", 
                                                         "dataOwner", 
                                                         "SysCreatedOn",
                                                         "SysCreatedBy",
                                                         "CustomerOrderLines"
                                                     });
                        customerOrderHeaderToBeChanged = UpdateLines(customerOrderHeader, customerOrderHeaderToBeChanged);
                        List<ICustomerOrderLine> linestoBeInserted = GetTheLineNumbersToBeInserted(customerOrderHeader);

                        foreach (var customerOrderLine in linestoBeInserted)
                        {
                            customerOrderHeaderToBeChanged.CustomerOrderLines.Add(customerOrderLine);
                            customerOrderLine.CustomerOrderHeader = customerOrderHeaderToBeChanged;
                        }

                        session.Update(customerOrderHeaderToBeChanged);
                    }

            //        transaction.Commit();
            }
            //    catch (Exception ex)
            //    {
            //        transaction.Rollback();
            //        throw ex;
            //    }
            //    finally
            //    {
            //        session.Close();
            //    }
            //}
            //throw new System.ArgumentException();

            return customerOrderHeader.OrderNumber;
        }


public class CustomerOrderHeaderService : ServiceBase, ICustomerOrderHeaderService
    {
        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerOrderHeaderService"/> class.
        /// </summary>
        /// <param name="sessionManager">
        /// The session manager.
        /// </param>
        public CustomerOrderHeaderService(ISessionManager sessionManager)
        {
            this.SessionManager = sessionManager;
        }

        #endregion

 public long Create(CustomerOrderHeader customerOrderHeader, bool firstTime)
        {


            using (var session = this.SessionManager.OpenSession())
            {
            //    var transaction = session.BeginTransaction();

            //    try
            //    {




                    if (firstTime)
                    {
                        foreach (var customerOrderLine in customerOrderHeader.CustomerOrderLines)
                        {
                            customerOrderLine.CustomerOrderHeader = customerOrderHeader;
                        }

                        customerOrderHeader.OrderNumber = this.NextOrderNumber();
                        session.Save(customerOrderHeader);
                    }
                    else
                    {

                        CustomerOrderHeader customerOrderHeaderToBeChanged =
                            this.FindByOrderNumber(customerOrderHeader.OrderNumber);

                        customerOrderHeaderToBeChanged.CopyDomainProperties(
                            customerOrderHeader, new[]
                                                     {
                                                         "Id", 
                                                         "Partner", 
                                                         "DataOwner", 
                                                         "dataOwner", 
                                                         "SysCreatedOn",
                                                         "SysCreatedBy",
                                                         "CustomerOrderLines"
                                                     });
                        customerOrderHeaderToBeChanged = UpdateLines(customerOrderHeader, customerOrderHeaderToBeChanged);
                        List<ICustomerOrderLine> linestoBeInserted = GetTheLineNumbersToBeInserted(customerOrderHeader);

                        foreach (var customerOrderLine in linestoBeInserted)
                        {
                            customerOrderHeaderToBeChanged.CustomerOrderLines.Add(customerOrderLine);
                            customerOrderLine.CustomerOrderHeader = customerOrderHeaderToBeChanged;
                        }

                        session.Update(customerOrderHeaderToBeChanged);
                    }

            //        transaction.Commit();
            }
            //    catch (Exception ex)
            //    {
            //        transaction.Rollback();
            //        throw ex;
            //    }
            //    finally
            //    {
            //        session.Close();
            //    }
            //}
            //throw new System.ArgumentException();

            return customerOrderHeader.OrderNumber;
        }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

奶气 2024-12-14 23:02:35

增加连接池限制可以帮助延长连接池的使用寿命,只要您不让服务器/网络饱和。

尽可能晚和早(分别)打开和关闭数据库连接。您可能希望将会话打开/关闭从按请求(或您正在使用的任何内容)切换为按使用。

在你的例子中,由于它是界面上的一个按钮,你可以暂时禁用它(使用 JavaScript)一段时间,这样用户就不能继续以比他们应该需要的速度更快的速度点击它。

无论如何,您应该在网络或 IIS 级别对传入请求进行速率限制。

Increase your connection pool limits can help make it last longer under this, as long as you don't saturate the server/network with too many.

Open and close database connections as late and early (respectively) as possible. You may want to switch your session open/close from per-request (or whatever you are using) to on-use.

In your case, since it's a button on the interface, you can temporarily disable it (with JavaScript) for a period of time so the user can't keep clicking it faster than they should ever need to.

Regardless, you should rate limit the incoming requests either at the network or IIS level.

橙幽之幻 2024-12-14 23:02:35

确保您没有在多个 NHibernate 会话之间共享对象。

如果会话 #1 加载会话 #2 尝试提交的对象,则可能会发生该错误。

Make sure that you aren't sharing objects across multiple NHibernate sessions.

That error could occur if Session #1 loads an object that Session #2 tries to commit.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文