Skip to main content

Session

Struct Session 

Source
pub struct Session(/* private fields */);
Expand description

The high-level interface you use to read and modify session data.

Session is an extractor, it can also be obtained with UserSession::get_session from an HttpRequest, WebRequest or RequestHead. All handles for the same request share the same state. Without session middleware, the state is not persisted between requests.

Once the session is purged, further handler mutations through set, remove, clear, or renew are ignored.

use ntex_session::Session;
use ntex::web::*;
use serde_json::error::Error as JsonError;

fn index(session: Session) -> Result<&'static str, JsonError> {
    // access session data
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok("Welcome!")
}

Implementations§

Source§

impl Session

Source

pub fn get<T: DeserializeOwned>( &self, key: &str, ) -> Result<Option<T>, JsonError>

Get a value from the session.

Returns Ok(None) if the key is not set.

§Errors

Returns an error if the stored JSON cannot be deserialized into T.

Source

pub fn set<T: Serialize>(&self, key: &str, value: T) -> Result<(), JsonError>

Set a value in the session.

Marks the session changed before serializing. Ignored if the session is purged, in which case the value is not serialized.

§Errors

Returns an error if the value cannot be serialized. The existing value is preserved, but the session remains marked changed.

Source

pub fn remove(&self, key: &str)

Remove a value from the session.

Ignored if the session is purged.

Source

pub fn clear(&self)

Remove all values from the session.

Ignored if the session is purged.

Source

pub fn purge(&self)

Remove the session, both client and server side.

All values are dropped, and later calls to set, remove, clear, and renew in the same request are ignored. The backend performs the removal.

Source

pub fn renew(&self)

Marks the session for reissue while preserving its existing state.

The backend chooses the renewal mechanism; CookieSession rewrites the cookie without rotating its signing or encryption key. Ignored if the session is purged.

Source

pub fn set_session<St>( data: impl Iterator<Item = (String, String)>, req: &WebRequest<St>, )

Load session state into the request.

Used by session backends before calling the inner service. Extends the current state, overwriting matching keys without changing the status. Values must be JSON encoded, as returned by Session::get_changes; this method does not validate them.

Source

pub fn get_changes( res: &mut WebResponse, ) -> (SessionStatus, Option<impl Iterator<Item = (String, String)> + use<>>)

Drains the state from the response’s request and returns its current status.

Used by session backends after the inner service returns. The state is moved out of all shared handles, but the status is not reset. Returns None for the state only if no session was created; otherwise returns Some, even for empty or unchanged state.

Trait Implementations§

Source§

impl<St> FromRequest<St> for Session

Extractor implementation for Session type.

use ntex_session::Session;
use serde_json::error::Error as JsonError;

fn index(session: Session) -> Result<&'static str, JsonError> {
    // access session data
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok("Welcome!")
}
Source§

type Error = !

The error returned when extraction fails. Read more
Source§

async fn from_request( _: &St, req: &HttpRequest, _: &mut Payload, ) -> Result<Session, Infallible>

Creates the extractor value for this request.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V