The Web Service under the web site reads the session value in the Web site.

Source: Internet
Author: User
Tags http authentication http cookie net xml
When using the Ajax: autocompleteextender control, the automatically completed data cannot be filtered by the current Login User, mainly because autocomplete. the method parameters automatically completed in asmx are fixed. User information cannot be transmitted to Web service by passing parameters. After checking some information on the Internet, we found that the Web service can directly access the web site session value. This is easy to handle. Only the declared enable session ( [ Webmethod ( Enablesession = True ), You can use it directly.

[Webmethod ( Enablesession = True )]
Public   String [] Getvendornamelist ( String Prefixtext, Int Count)
{
If (Count =   0 )
{
Count =   10 ;
}
Int Currentoperatoruserid = Getcurrentoperatoruserid ();
String Selectedorderfrom =   Session [ "Selectedorderfrom" ]  ! =   Null   ? Session [ " Selectedorderfrom " ]. Tostring (): Null ;
Datatable vendortable =   New Autocompleteentitymethod (). getautocompletevendortable (
Prefixtext, count, " Vendorname " , Currentoperatoruserid, selectedorderfrom );
List < String > Items =   New List < String > (Count );
For ( Int I =   0 ; I < Vendortable. Rows. Count; I ++ )
{
Items. Add (vendortable. Rows [I] [ 0 ]. Tostring ());
}

ReturnItems. toarray ();
}


Refer to the following two articlesArticle:

Asp.net status in Web Service
Introduction

NetworkProgramThe most common problem developers encounter is how to maintain status information in stateless HTTP-based interactions. There are many smart ways to solve the stateless problem of HTTP, for example, you can send application data packets repeatedly for each request, map requests to specific users using the HTTP authentication mechanism, and store the status of a series of requests using cookies. The Asp.net technology provides a very effective solution to maintain the state. This solution hides the details of all difficult and challenging tasks. Users only need to simply use the system. web. sessionstate. httpsessionstate class. At the same time, you can also use this class in the Web service method as in the web page (. aspx) of the Asp.net program. There is only a small difference.

Asp.netSessionObject Overview

The session status information of Asp.net is maintained through two mechanisms. One is to use cookies. When the client sends a request to the server, the server sends a response message that is appended with the HTTP set-Cookie header, the cookie value is saved in the form of a key/value pair. In all synchronous requests to the same server, the client sends a cookie key/value pair in the HTTP cookie header. Then the server can correspond concurrent requests to the initial requests. Asp.net uses a cookie that saves the session ID to maintain the session status. This ID is used to find the corresponding httpsessionstate instance for a specific user. The httpsessionstate class only provides a common dataset, where you can save any information you need.

Another mechanism for Asp.net to maintain the status is that cookie is not required. Some browsers are set by users to prohibit the use of cookies or simply do not support cookies. Asp.net provides a mechanism to solve this problem, the main principle is to redirect a request to a URL containing the Asp.net status ID. When the request is accepted, the ID embedded in the URL is intercepted, and the server finds an appropriate instance of the httpsessionstate class through this ID. This method works well in http get requests, but in. Net XML Web ServiceCode.

It must be noted that in some cases, it is better to store information directly in cookies than in sessions. Avoiding session can save server resources, and you do not need to consider some annoying problems, for example, to locate a specific session object or session object, the object is removed due to a long request delay or is not necessary to be retained on the server until it expires. However, if you have execution information that you do not want to share with the users of your services, or private data that you do not want to transmit over unencrypted channels, or you think it is impractical to insert the data into the HTTP header, so you should use httpsessionstate in Asp.net, which will make it easy for you to solve these problems. The httpsessionstate class returns an index key to map a specific user to an instance of the httpsessionstate class that saves information for the user. In short, both Asp.net's httpsessionstate class and HTTP cookie can be used in Asp.net web service.

Why is HTTP-based mechanism used in XML Web Service to maintain the status?

There are many methods in the SOAP request to maintain the status. A practical method is to include some session ID information like ASP in the SOAP header, but the problem is that you have to: 1) write the server code by yourself, and 2) make sure that your customers treat your SOAP header containing the session ID as they do with HTTP cookies and attach it to each request and send it back to you. Of course, there are many times that it is very convenient to use the SOAP header, but there are also many times that it is better to use HTTP-based methods.

It is easy to use session in Asp.net to maintain state information. The httpsessionstate class encapsulates the details of session state storage. Most clients already understand that they must return the cookie set by the server, and the httpsessionstate class also supports underlying transmission that is commonly used in soap communication. Therefore, it is obvious that using Asp.net's session mechanism is a wise choice to meet the state control requirements.

Enable the server to support sessions

In Asp.net, the web method status support is disabled by default. You must explicitly activate the session support for each web method that uses the session status. To activate a session, you can add an enablesession option to the webmethod attribute of your function and set its value to true. The following code demonstrates how to activate a session and access the session status information in the method.

[VB.net]

<Webmethod (enablesession: = true)> _
Public Function incrementsessioncounterx () as integer
Dim counter as integer
If context. Session ("counter") is nothing then
Counter = 1
Else
Counter = context. Session ("counter") + 1
End if
Context. Session ("counter") = counter
Return counter
End Function

As expected, If you activate session support for a web method, it does not mean that session support for other web methods is also activated. In fact, if the enablesession option of the web method is not explicitly set to true, the value of the context. Session attribute will be null.

Assume that the session is disabled by setting the Web. config file. Even if you use the enablesession option in the webmethod attribute, the value of context. Session will always be null. The/configuration/system. Web/sessionstate item in the web. config file has a mode parameter, which determines the method used by your Asp.net program to maintain the session state. This parameter is set to "inproc" by default. In this case, the httpsessionstate object will be stored in the memory zone of the Asp.net process. If it is set to "off", the session support of the Asp.net program will be disabled.

On the server side, the valid range of Asp.net session status is only a given Asp.net application, this means that an httpsessionstate instance can only be used by Asp.net requests activated for all sessions sent by a specific user to a virtual directory. That is to say, requests from the same session ID to other virtual directories will cause Asp.net to fail to find the corresponding session object-because the session ID is not set for this Asp.net application. Asp.net does not differentiate requests to aspx and asmx files until the request needs to use session objects. Therefore, theoretically, you can share session status information between a web method call and a common aspx file. However, we will see that some client problems make this idea not so easy to implement.

When setting an HTTP cookie, you can specify its expiration time. The expiration time indicates how long the client will return the cookie to the server. If a cookie does not have an expiration time set, it is returned only when the process processes the request. For example, ie will always return the cookie unless you close a specific window in the browser. Asp.net's cookie used to save session IDs has no expiration time. Therefore, if multiple processes on a client send HTTP requests to your server, they will not share the same httpsessionstate object, even the two processes run at the same time.

If you want to process concurrent web service calls from the same process, these requests will be sorted on the server, so that only one request is executed at a certain time. The Web Service of Asp.net is not as common. the ASPX page supports read-only access to the httpsessionstate object by concurrent processes with multiple requests. All web method calls activated by sessions have the read/write access permission, therefore, it must be sorted.

Web Service non-SOAP header (Session) authentication method

Recently I am working on a program Web Service. You must verify the account before using it. Web The method provided by the Service first comes up with the method of attaching account information to the SOAP header, but other colleagues in the company found a lot of inconvenience when calling non-. net programs. Another Google town found a session method, which is an example we saw when we looked for "multipart upload large attachments by web service, it is no wonder that the expected results are not found during web service verification. The code is relatively simple. The main code is as follows: View plaincopy to clipboardprint?
/// <Summary>
/// Authorization verification: This method is called when you call web service. After the call is completed, it is like a normal website login. As long as the session does not time out, you do not need to call this method again.
/// </Summary>
/// <Param name = "appname"> program name </param>
/// <Param name = "appauthorizecode"> authorization code </param>
/// <Returns> </returns>
[Webmethod (enablesession = true, messagename = "Authorization Verification")]
Public bool checkauthorize (string appname, string appauthorizecode)
{
If (appname = "account name" & appauthorizecode = "123456 ")
Session ["login"] = true;
Else
Session ["login"] = false;

Return (bool) session ["login"];
}

/// <Summary>
/// Add the file and then call
/// </Summary>
/// <Param name = "model"> archive object class </param>
/// <Returns> </returns>
[Webmethod (enablesession = true, messagename = "add file")]
Public String addarchive (model. Archives Model)
{
Try
{

If (session ["login"]! = NULL & session ["login"]. Equals (true) // you can check whether the session value has been verified. Before each method, you must determine
{
// The following code is the sample code. You can place your own code as needed.
Bll. Archives BLL = new BLL. Archives (); // instantiate the archive operation class

If (BLL. addarchive (model) // Add a file
Return "file added successfully ";
Else
Return "failed to add file ";
}
Else
Return "Verification Failed ";
}
Catch (exception ERR)
{
Return err. message;
}
}

/// <Summary>
/// Authorization verification: This method is called when you call web service. After the call is completed, it is like a normal website login. As long as the session does not time out, you do not need to call this method again.
/// </Summary>
/// <Param name = "appname"> program name </param>
/// <Param name = "appauthorizecode"> authorization code </param>
/// <Returns> </returns>
[Webmethod (enablesession = true, messagename = "Authorization Verification")]
Public bool checkauthorize (string appname, string appauthorizecode)
{
If (appname = "account name" & appauthorizecode = "123456 ")
Session ["login"] = true;
Else
Session ["login"] = false;

Return (bool) session ["login"];
}

/// <Summary>
/// Add the file and then call
/// </Summary>
/// <Param name = "model"> archive object class </param>
/// <Returns> </returns>
[Webmethod (enablesession = true, messagename = "add file")]
Public String addarchive (model. Archives Model)
{
Try
{

If (session ["login"]! = NULL & session ["login"]. Equals (true) // The session value is determined here,

Whether the verification is successful. Before each method, you must determine
{
// The following code is the sample code. You can place your own code as needed.
Bll. Archives BLL = new BLL. Archives (); // instantiate the archive operation class

If (BLL. addarchive (model) // Add a file
Return "file added successfully ";
Else
Return "failed to add file ";
}
Else
Return "Verification Failed ";
}
Catch (exception ERR)
{
Return err. message;
}
} We can see that the "enablesession = true" attribute is used for session verification.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.