Come posso accedere alla sessione in un metodo web?


87

Posso usare i valori di sessione all'interno di un WebMethod?

Ho provato a utilizzare System.Web.Services.WebMethod(EnableSession = true)ma non riesco ad accedere al parametro Session come in questo esempio :

    [System.Web.Services.WebMethod(EnableSession = true)]
    [System.Web.Script.Services.ScriptMethod()]
    public static String checaItem(String id)
    { 
        return "zeta";
    }

ecco il JS che chiama il metodo web:

    $.ajax({
        type: "POST",
        url: 'Catalogo.aspx/checaItem',
        data: "{ id : 'teste' }",
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        }
    });

4
Pubblicare un esempio di codice ci aiuterà a fornirti una risposta.
— volpav

Ricevi un'eccezione?
— Darin Dimitrov

1
Nell'esempio sopra non vedo che stai cercando di accedere a nessun valore di sessione. Devi prima impostare la var della sessione, quindi accedervi come il link che hai pubblicato. return (int) Session ["Conversions"];
— capdragon

@volpav ha fornito il codice di esempio.
— BrainSlugs83

No, @capdragon la proprietà Session della pagina non esiste per i metodi statici (i WebMethod devono essere statici) - sta chiedendo dove trovare la proprietà - come pubblicato di seguito, risiede nell'attuale HttpContext.
— BrainSlugs83

Risposte:


119

Puoi usare:

HttpContext.Current.Session

Ma lo sarà a nullmeno che non specifichi anche EnableSession=true:

[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{ 
    return "zeta";
}

18
Ironia della sorte, questo è quello che stavo già facendo, solo che non funzionava per me. HttpContext.Current.Session.Count restituiva 0 (ovvero nessun elemento in Session). Per me, la risposta era nella domanda, la modifica di [WebMethod] in [WebMethod (EnableSession = true)] ha funzionato. Woot!
— BrainSlugs83

4
Ricordati di configurare web.config <sessionState mode = "InProc" />
— Moesio

10

Esistono due modi per abilitare la sessione per un metodo Web:

1. [WebMethod(enableSession:true)]

2. [WebMethod(EnableSession = true)]

Il primo con l'argomento del costruttore enableSession:truenon funziona per me. Il secondo con EnableSessionopere immobiliari.


Non riesco a capire se il primo compila anche - credo che non lo sia. Il secondo funziona perché stai impostando la proprietà (solo ovvio qui XD).
— MVCDS

@ MVCDS Perché pensi che non dovrebbe essere compilato? Puoi trovare un costruttore pubblico WebMethodAttribute(Boolean)in docs.
— Warlock

Hai assolutamente ragione. Si comporta diversamente se non si imposta il nome del parametro? Perché se lo fa, è successo qualcosa di molto strano durante la codifica di costruttori (per attributi).
— MVCDS

1

Per abilitare la sessione dobbiamo usare [WebMethod (enableSession: true)]

[WebMethod(EnableSession=true)]
public string saveName(string name)
{
    List<string> li;
    if (Session["Name"] == null)
    {
        Session["Name"] = name;
        return "Data saved successfully.";

    }

    else
    {
        Session["Name"] = Session["Name"] + "," + name;
        return "Data saved successfully.";
    }


}

Ora per recuperare questi nomi usando la sessione possiamo procedere in questo modo

[WebMethod(EnableSession = true)]
    public List<string> Display()
    {
        List<string> li1 = new List<string>();
        if (Session["Name"] == null)
        {

            li1.Add("No record to display");
            return li1;
        }

        else
        {
            string[] names = Session["Name"].ToString().Split(',');
            foreach(string s in names)
            {
                li1.Add(s);
            }

            return li1;
        }

    }

quindi recupererà tutti i nomi dalla sessione e dallo spettacolo.


0

Puoi provare in questo modo [WebMethod] public static void MyMethod (string ProductID, string Price, string Quantity, string Total) // Aggiungi un nuovo parametro qui {db_class Connstring = new db_class (); provare {

            DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];

            if (dt == null)
            {
                DataTable dtable = new DataTable();

                dtable.Clear();
                dtable.Columns.Add("ProductID");// Add new parameter Here
                dtable.Columns.Add("Price");
                dtable.Columns.Add("Quantity");
                dtable.Columns.Add("Total");
                object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
                dtable.Rows.Add(trow);
                HttpContext.Current.Session["aaa"] = dtable;                   
            }
            else
            {
                object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
                dt.Rows.Add(trow);
                HttpContext.Current.Session["aaa"] = dt;
            }


        }
        catch (Exception)
        {
            throw;
        }
    }


0

In C #, nel codice dietro la pagina utilizzando il metodo Web,

[WebMethod(EnableSession = true)]
        public static int checkActiveSession()
        {
            if (HttpContext.Current.Session["USERID"] == null)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }

E, nella pagina aspx,

$.ajax({
                type: "post",
                url: "",  // url here
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: '{ }',
                crossDomain: true,
                async: false,
                success: function (data) {
                    returnValue = data.d;
                    if (returnValue == 1) {

                    }
                    else {
                        alert("Your session has expired");
                        window.location = "../Default.aspx";
                    }
                },
                error: function (request, status, error) {
                    returnValue = 0;
                }
            });
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.