У меня есть статический класс Web
, в который я добавляю любые свойства, полезные для всего приложения.
Отличие состоит в том, что объекты Request
, Response
и Session
не доступны напрямую. Итак, у меня есть 3 вспомогательные функции, которые возвращают текущие объекты Request
, Response
и Session
, если они доступны.
Итак, свойство Person person
будет выглядеть так:
using System;
using System.Web;
using System.Web.SessionState;
namespace MyWebApp
{
public static class Web
{
private static HttpRequest request
{
get
{
if (HttpContext.Current == null) return null;
return HttpContext.Current.Request;
}
}
private static HttpResponse response
{
get
{
if (HttpContext.Current == null) return null;
return HttpContext.Current.Response;
}
}
private static HttpSessionState session
{
get
{
if (HttpContext.Current == null) return null;
return HttpContext.Current.Session;
}
}
public static Person person
{
get
{
// Here you can change what is returned when session is not available
if (session == null) return null;
if(session["Person"] == null) {
session["Person"] = new Person();
}
return session["Person"] as Person;
}
set
{
// Here you can change how to handle the case when session is not available
if (session == null) return;
session["Person"] = value;
}
}
}
}
Чтобы использовать его, в коде Page
или UserControl
вы можете написать
// get
var x = MyWebApp.Web.person;
// set
MyWebApp.Web.person = x;