简体   繁体   English

如何在库中添加到modelstate?

[英]How do I add to modelstate in my library?

In my DB class I have a function like this: 在我的数据库类中,我有一个像这样的函数:

        //Check if the user login exists in the DB if this is a new user. 
        if ((userModelItem.UserId == 0) || (userModelItem.UserId == null))
        {
            if (_db.ABUsers.Count(s => s.Loggin1 == user.Loggin1 || s.Loggin1 == user.Loggin2 ||
                s.Loggin2 == user.Loggin1 || s.Loggin2 == user.Loggin2) > 0)
            {
                var exLog = new ExceptionThrowHandler();
                exLog.SaveNewException("SaveUserModelItem", "ABUserRepository", "Loggin1 or loggin2 exists in DB");
                return null;

Is it possible to here also try and add an error to the modelstate without having to pass the modestate as an object to the function? 是否有可能在这里也尝试将错误添加到模型状态而不必将modestate作为对象传递给函数? IE can I get hold of the modestate from httpcontext.current or something? IE浏览器可以从httpcontext.current或其他获得状态吗?

IE can I get hold of the modestate from httpcontext.current or something? IE浏览器可以从httpcontext.current或其他获得状态吗?

Although you could use something like System.Web.HttpContext I would strongly recommend against it . 尽管您可以使用类似System.Web.HttpContext之类的东西,但我还是强烈建议您不要使用它 Using an environment value like this would make your code impossible to test through unit testing. 使用这样的环境值将使您的代码无法通过单元测试进行测试。

Your best bet is to either pass the context value down to the class or return something so that the appropriate layer access the HTTP context. 最好的选择是将上下文值传递给该类或返回某些内容,以便适当的层访问HTTP上下文。

Hard to give much advice without knowing where you're trying to call this function from as this affects what might be available to you. 在不知道您试图从何处调用此函数的情况下,很难给出很多建议,因为这会影响您可能会使用的功能。 As far as I know it's not possible to access ModelState from HttpContext.Current though knowing more about your circumstance might help find another work around. 据我所知,不可能从HttpContext访问ModelState.Current,尽管更多地了解您的情况可能会帮助您找到其他解决方法。

Without knowing more the best I could suggest would be a helper function at an intermediate layer that does take modelstate and then calls your DB function, tests the result to see if it needs to affect the modelstate, and then returns the original response. 在不了解更多信息的情况下,我可能会建议在中间层使用一个帮助程序函数,该函数确实接受模型状态,然后调用您的数据库函数,测试结果以查看是否需要影响模型状态,然后返回原始响应。

Why not throw an exception from the data access layer, catch it in the calling controller, and update the modelstate there? 为什么不从数据访问层引发异常,将其捕获在调用控制器中,并在那里更新modelstate? This seems like a much cleaner separation of concerns to me. 对我来说,这似乎是一种更加清晰的关注点分离。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM