4

可以 - 最佳实践 - 使用第二层重定向用户吗?

例如:

public static void ForceLogin()
{
    HttpCookie cookie = HttpContext.Current.Request.Cookies[cookieName];

    if (cookie != null)
    {
        if (Regex.IsMatch(cookie.Value, "^[0-9]+\\.[a-f0-9]+$"))
        {
            using (EibxDataContext db = new EibxDataContext())
            {
                int count = db.Logins.Count(l => l.Password == cookie.Value);

                if (count == 1)
                {
                    return;
                }
            }
        }
    }

    HttpContext.Current.Response.Redirect("~/Login.aspx");
}

在最后一行,我使用业务/服务逻辑层将用户重定向到登录页面。

这应该在表示层中完成吗?

4

3 回答 3

8

Absolutely not. The business logic layer should make the decision, the UI layer should do the redirect. The business layer shouldn't know anything about HttpContext nor should it be directly reading cookies. Pass the relevant information into the business layer so that the business layer can make the decision, and pass the decision out to the UI layer so that it can work on the resultant decision.

Here's the reason... what if the business layer is used from a web service? How can the business layer do a redirect in that instance? Or suppose it's used with a non-web client? Redirection has no meaning in that context. If you change your UI layer, that should not affect your business logic layer, and mixing in redirects and cookie reading into the business layer will necessitate that with the proposed design.

于 2008-12-27T17:19:49.890 回答
5

这取决于您如何定义图层;例如,我的“业务逻辑”通常是与我要解决的问题相关的逻辑,对 UI 一无所知。因此它无法进行重定向,因为它无法访问请求/响应。

Personally, I'd do this at the UI layer; dealing with the raw interactions such as being gate-keeper and custodian is part of the UI layer's job for a web app. IMO. For example, via an http-module, which is (by definition) a UI-level component.

于 2008-12-27T17:13:57.187 回答
0

我会说你在业务逻辑中这样做是正确的。表示层不应该做出有关路由的决定。

于 2008-12-27T17:09:01.923 回答