2011-01-21 15 views
70

Posso usare i valori di sessione all'interno di WebMethod?Come posso accedere alla sessione in un webmethod?

Ho provato con System.Web.Services.WebMethod(EnableSession = true) ma non posso accedere al parametro Session come in this example:

[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 WebMethod:

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

La pubblicazione di un esempio di codice ci aiuterà a fornire una risposta. – volpav

+0

Stai ricevendo un'eccezione? –

+1

Nell'esempio precedente non vedo che si sta tentando di accedere a qualsiasi valore di sessione. Devi prima impostare la variabile var e poi accedervi come il link che hai postato. return (int) Session ["Conversions"]; – capdragon

risposta

94

È possibile utilizzare:

HttpContext.Current.Session 

Ma sarà null a meno che anche voi pecify EnableSession=true:

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

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

+3

Ricordarsi di configurare il web.config Moesio

10

Ci sono due modi per attivare la sessione per un metodo Web:

1. [WebMethod(enableSession:true)] 

2. [WebMethod(EnableSession = true)] 

Il primo con argomento del costruttore enableSession:true non funziona per me. Il secondo con opere di proprietà EnableSession.

+0

Non riesco a [capire] (https://msdn.microsoft.com/en-us/library/system.web.services.webmethodattribute%28v=vs.110%29. aspx) se il primo compila anche - credo che non lo sia. Il secondo funziona perché stai impostando la proprietà (è solo ovvio qui XD). – MVCDS

+0

@MVCDS Perché pensi che non dovrebbe essere compilato? È possibile trovare un costruttore pubblico 'WebMethodAttribute (Boolean)' nei documenti. – Warlock

+0

Hai assolutamente ragione. Si comporta in modo diverso se non si imposta il nome del parametro? Perché se lo fa, qualcosa di molto strano si è verificato quando stavano codificando costruttori (per attributi). – MVCDS

0

Si può provare in questo modo [WebMethod] MyMethod public static void (stringa IDProdotto, string Prezzo, string Quantità, string totale) // Aggiungi 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

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 a retrive i nomi utilizzando la sessione siamo in grado di andare 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; 
     } 

    } 

così lo farà recuperare tutti i nomi dalla sessione e mostrare.

Problemi correlati