Идеи ASP.net "BasePage" класса

Что делают прохладная функциональность и методы Вы добавляете к своему ASP.net BasePage : System.Web.UI.Page классы?

Примеры

Вот что-то, что я использую для аутентификации, и я хотел бы услышать Ваши мнения об этом:

protected override void OnPreInit(EventArgs e)
{
    base.OnPreInit(e);

    // Authentication code omitted... Essentially same as below.

    if (_RequiresAuthentication && !(IsAuthorized))
    {
        RespondForbidden("You do not have permissions to view this page.", UnauthorizedRedirect);
        return;
    }
}

// This function is overridden in each page subclass and fitted to each page's
// own authorization requirements.
// This also allows cascading authorization checks,
// e.g: User has permission to view page? No - base.IsAuthorized - Is user an admin?
protected virtual bool IsAuthorized
{
    get { return true; }
}

Мой класс BasePage содержит экземпляр этого класса:

public class StatusCodeResponse {

    public StatusCodeResponse(HttpContext context) {
        this._context = context;
    }

    /// <summary>
    /// Responds with a specified status code, and if specified - transfers to a page.
    /// </summary>
    private void RespondStatusCode(HttpContext context, System.Net.HttpStatusCode status, string message, string transfer)
    {
        if (string.IsNullOrEmpty(transfer))
        {
            throw new HttpException((int)status, message);
        }

        context.Response.StatusCode = (int)status;
        context.Response.StatusDescription = message;
        context.Server.Transfer(transfer);
    }

    public void RespondForbidden(string message, string transfer)
    {
        RespondStatusCode(this._context, System.Net.HttpStatusCode.Forbidden, message, transfer);
    }

    // And a few more like these...

}

Как примечание стороны, это могло быть выполнено с помощью дополнительных методов для HttpResponse объект.

И другой метод я нахожу довольно удобными для парсинга querystring международные аргументы:

public bool ParseId(string field, out int result)
{
    return (int.TryParse(Request.QueryString[field], out result) && result > 0);
}
11
задан 5 revs 2 February 2010 в 17:05
поделиться

7 ответов

  • Ссылка, связанная с сеансом, какой-то сложный объект в BaseePage, который отображает на сеанс и разоблачить его как свойство.
  • Делать такие вещи, как заполнение объекта крошилки.

Но самое важное: не делает ваш базовыйaupage в какой-то класс помощника . Не добавляйте вещи, как Parseid () , это просто смешно.


Также, основываясь на первом посте: Сделайте такие вещи, как несавторизованные Аннотация . Таким образом, вы не создаете гигантские отверстия безопасности, если кто-то забудет, что есть какой-то виртуальный метод.

5
ответ дан 3 December 2019 в 08:29
поделиться

код авторизации Помещения в базовой странице обычно является не хорошей идеей. Проблема, что происходит, если вы забываете получать страницу, которой нужна авторизация от базовой страницы? У вас будет дыра в системе безопасности.

намного лучше использовать HttpModule, так, чтобы можно было прервать запросы на все страницы и удостовериться, что пользователи авторизовываются даже, прежде чем HttpHandler имеет шанс работать.

кроме того, как другие сказали, и в соответствии с принципами OO, лучше только иметь методы в вашей базовой странице, которые на самом деле касаются самой Страницы. Если они не ссылаются на "это", они должны, вероятно, быть в классе помощника - или возможно являются дополнительными методами.

1
ответ дан 3 December 2019 в 08:29
поделиться

nbtstat используется для выполнения этого из командной строки с именем компьютера или IP-адресом. Я давно не смотрел на это.

-121--4043561-
C:\workspaces\silverlight> start-transcript -?

NAME
    Start-Transcript

SYNOPSIS
    Creates a record of all or part of a Windows PowerShell session in a text file.


SYNTAX
    Start-Transcript [[-Path] <string>] [-Append] [-Force] [-NoClobber] [-Confirm] [-WhatIf] [<CommonParameters>]


DESCRIPTION
    The Start-Transcript cmdlet creates a record of all or part of a Windows PowerShell session in a text file. The transcript includes all command that the user
     types and all output that appears on the console.


RELATED LINKS
    Online version: http://go.microsoft.com/fwlink/?LinkID=113408
    Stop-Transcript 

REMARKS
    To see the examples, type: "get-help Start-Transcript -examples".
    For more information, type: "get-help Start-Transcript -detailed".
    For technical information, type: "get-help Start-Transcript -full".

Примечание № 1: записывается только запись в выходной поток основной консоли, а не предупреждение/ошибка/отладка.

Примечание № 2: если требуется запись собственных консольных приложений, потребуется небольшое обходное решение

-121--2100088-

Инициализация культуры путем переопределения метода InitialityCulture () (набор культуры и ui из cookie или DB).

Некоторые из моих приложений являются брендируемыми, затем здесь я делаю некоторые «брендинговые» вещи тоже.

1
ответ дан 3 December 2019 в 08:29
поделиться
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace MySite
{
    /// <summary>
    /// Base class with properties for meta tags for content pages
    /// http://www.codeproject.com/KB/aspnet/PageTags.aspx
    /// http://weblogs.asp.net/scottgu/archive/2005/08/02/421405.aspx
    /// </summary>
    public partial class BasePage : System.Web.UI.Page
    {
        private string keywords;
        private string description;


        /// <SUMMARY>
        /// Gets or sets the Meta Keywords tag for the page
        /// </SUMMARY>
        public string Meta_Keywords
        {
            get
            {
                return keywords;
            }
            set
            {
                // Strip out any excessive white-space, newlines and linefeeds
                keywords = Regex.Replace(value, "\\s+", " ");
            }
        }

        /// <SUMMARY>
        /// Gets or sets the Meta Description tag for the page
        /// </SUMMARY>
        public string Meta_Description
        {
            get
            {
                return description;
            }
            set
            {
                // Strip out any excessive white-space, newlines and linefeeds
                description = Regex.Replace(value, "\\s+", " ");
            }
        }


        // Constructor
        // Add an event handler to Init event for the control
        // so we can execute code when a server control (page)
        // that inherits from this base class is initialized.
        public BasePage()
        {
            Init += new EventHandler(BasePage_Init); 
        }


        // Whenever a page that uses this base class is initialized,
        // add meta keywords and descriptions if available
        void BasePage_Init(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Meta_Keywords))
            {
                HtmlMeta tag = new HtmlMeta();
                tag.Name = "keywords";
                tag.Content = Meta_Keywords;
                Header.Controls.Add(tag);
            }

            if (!String.IsNullOrEmpty(Meta_Description))
            {
                HtmlMeta tag = new HtmlMeta();
                tag.Name = "description";
                tag.Content = Meta_Description;
                Header.Controls.Add(tag);
            }
        }
    }
}
3
ответ дан 3 December 2019 в 08:29
поделиться

Я использую этот меток и спасибо за ваш,

/// <summary>
        /// Displays the alert.
        /// </summary>
        /// <param name="message">The message to display.</param>
        protected virtual void DisplayAlert(string message)
        {
            ClientScript.RegisterStartupScript(
                            GetType(),
                            Guid.NewGuid().ToString(),
                            string.Format("alert('{0}');", message.Replace("'", @"\'")),
                            true
                        );
        }

        /// <summary>
        /// Finds the control recursive.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>control</returns>
        protected virtual Control FindControlRecursive(string id)
        {
            return FindControlRecursive(id, this);
        }

        /// <summary>
        /// Finds the control recursive.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <param name="parent">The parent.</param>
        /// <returns>control</returns>
        protected virtual Control FindControlRecursive(string id, Control parent)
        {
            if (string.Compare(parent.ID, id, true) == 0)
                return parent;

            foreach (Control child in parent.Controls)
            {
                Control match = FindControlRecursive(id, child);

                if (match != null)
                    return match;
            }

            return null;
        }
1
ответ дан 3 December 2019 в 08:29
поделиться

Я бы использовал общий, с которым вы могли бы справиться внешне...

/// <summary>
/// Generic object copy of the same type
/// </summary>
/// <typeparam name="T">The type of object to copy</typeparam>
/// <param name="ObjectSource">The source object to copy</param>
public T CopyObject<T>(T ObjectSource)
{
    T NewObject = System.Activator.CreateInstance<T>();

    foreach (PropertyInfo p in ObjectSource.GetType().GetProperties())
        NewObject.GetType().GetProperty(p.Name).SetValue(NewObject, p.GetValue(ObjectSource, null), null);

    return NewObject;
}
-121--531295-

Планы выполнения обычно будут идентичными в этих случаях, но пока вы не увидите, как коэффициенты оптимизатора во всех других аспектах индексов и т.д., вы действительно никогда не узнаете.

-121--712606-

Я наследую от System.Web.UI.Page, когда мне нужны определенные свойства и каждая страница. Это полезно для приложения aweb, реализующего вход в систему. На страницах членства я использую собственный базовый класс, чтобы получить доступ к таким свойствам, как UserID, UserName и т.д. Эти свойства переносят переменные сеанса

0
ответ дан 3 December 2019 в 08:29
поделиться

Вместе с уже упомянутыми метаданными (в основном , устаревшими в ASP.NET 4.0, с новыми Page.MetaDescription и Page. MetaKeywords properties), у меня также были методы добавления других заголовочных ссылок на мою страницу, таких как специфические для страницы CSS, или такие вещи как канонические ссылки, RSS ссылки и т.д.:

/// <overloads>
/// Adds a CSS link to the page. Useful when you don't have access to the
///  HeadContent ContentPlaceHolder. This method has 4 overloads.
/// </overloads>
/// <summary>
/// Adds a CSS link.
/// </summary>
/// <param name="pathToCss">The path to CSS file.</param>
public void AddCss(string pathToCss) {
    AddCss(pathToCss, string.Empty);
}

/// <summary>
/// Adds a CSS link in a specific position.
/// </summary>
/// <param name="pathToCss">The path to CSS.</param>
/// <param name="position">The postion.</param>
public void AddCss(string pathToCss, int? position) {
    AddCss(pathToCss, string.Empty, position);
}

/// <summary>
/// Adds a CSS link to the page with a specific media type.
/// </summary>
/// <param name="pathToCss">The path to CSS file.</param>
/// <param name="media">The media type this stylesheet relates to.</param>
public void AddCss(string pathToCss, string media) {
    AddHeaderLink(pathToCss, "text/css", "Stylesheet", media, null);
}

/// <summary>
/// Adds a CSS link to the page with a specific media type in a specific
/// position.
/// </summary>
/// <param name="pathToCss">The path to CSS.</param>
/// <param name="media">The media.</param>
/// <param name="position">The postion.</param>
public void AddCss(string pathToCss, string media, int? position) {
    AddHeaderLink(pathToCss, "text/css", "Stylesheet", media, position);
}

/// <overloads>
/// Adds a general header link. Useful when you don't have access to the
/// HeadContent ContentPlaceHolder. This method has 3 overloads.
/// </overloads>
/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
public void AddHeaderLink(string href, string type) {
    AddHeaderLink(href, type, string.Empty, string.Empty, null);
}

/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
public void AddHeaderLink(string href, string type, string rel) {
    AddHeaderLink(href, type, rel, string.Empty, null);
}

/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
/// <param name="media">The media target of the link.</param>
public void AddHeaderLink(string href, string type, string rel, string media)
{
    AddHeaderLink(href, type, rel, media, null);
}

/// <summary>
/// Adds a general header link.
/// </summary>
/// <param name="href">The path to the resource.</param>
/// <param name="type">The type of the resource.</param>
/// <param name="rel">The relation of the resource to the page.</param>
/// <param name="media">The media target of the link.</param>
/// <param name="position">The postion in the control order - leave as null
/// to append to the end.</param>
public void AddHeaderLink(string href, string type, string rel, string media, 
                          int? position) {
  var link = new HtmlLink { Href = href };

  if (0 != type.Length) {
    link.Attributes.Add(HtmlTextWriterAttribute.Type.ToString().ToLower(), 
                        type);
  }

  if (0 != rel.Length) {
    link.Attributes.Add(HtmlTextWriterAttribute.Rel.ToString().ToLower(),
                        rel);
  }

  if (0 != media.Length) {
    link.Attributes.Add("media", media);
  }

  if (null == position || -1 == position) {
    Page.Header.Controls.Add(link);
  }
  else
  {
    Page.Header.Controls.AddAt((int)position, link);
  }
}
3
ответ дан 3 December 2019 в 08:29
поделиться
Другие вопросы по тегам:

Похожие вопросы: