Building a Web service for asp.net application settings

Source: Internet
Author: User
Tags config configuration settings error handling iis sessions web services root directory
Asp.net|web|web Services | Program One, what is application settings

Application settings typically refer to a series of parameters that are closely related to the application. In a form-based Windows application, application settings include parameters such as location, size, and other parameters that affect the layout of the application, color, shape, and so on that affect the appearance of the application, and also include settings for the language, culture, and so on of the application, as well as data sources and connection strings. These parameter settings are widely applied in program development, and are used to maintain consistency and continuity of the application, such as saving the form size, position, and background color at the end of the application, restoring those settings the next time the application is executed, and other parameters that make the program code more concise and efficient. For example, save the database connection string for multiple calls.

Unlike form-based Windows applications, web-based asp.net applications have their own specificity, which is network-oriented. This determines that the ASP.net application settings include, in addition to the above parameters,

# Security mechanisms such as authentication and authorization

# Network Transport protocol types and HTTP handlers for specific types of documents

# Transaction Processing

# Timeout for all page settings

# custom error page to replace default IIS error page

# Sessions and Session state information

# Page Caching behavior

# Customization and extension

Visible, the asp.net application sets a richer parameter type. In practice, they are used not only to improve the security and efficiency of applications, but also to manage specific users and customize requirements.

Second, why to set the ASP.net application external to the Web service

There is no need to mention the benefits of Web services, and the media hype and widespread use in many areas is enough to explain the problem. Still, the point here is that Web services are actually asp.net applications, but are being organized again. In particular, Web services provide implementations for sharing objects between different applications. With simple references, you can access the functionality implemented by another program in a program, not just in asp.net, but only through a browser. Clearly, Web services also have many of the features and features that a general asp.net application has. Both ASP.net and Web services have state management capabilities as a typical example.

However, what are the advantages of setting an external asp.net application to a Web service? On one hand, you can get answers to the reusability of software (applications), and imagine that if a client application (source) needs to use the setting parameters of another application (the target), configuring the target application settings as a Web service can be easily invoked in the source application. It's like configuring the same settings on this computer. On the other hand, Web services (asp.net application applications) special mechanisms for storing their application settings (that is, the Web.config file storage settings described below) make it possible for applications to upgrade and Xcopy deploy across platforms, across the Internet, and in applications.

Third, storage asp.net application settings

We should already know that windows-based application settings are generally saved in the registry. Save a specific set value by writing a key-value pair to the registry. Then, by reading the registry's key value pair, the appropriate setting value is removed. It seems that the process itself is not complicated, plus. NET Framework provides rich class library support for reading and writing to the registry, making it simpler to manipulate the registry to read and write application settings (see special articles for registry reads and writes, no more here).

However, the registry itself is a fairly sensitive area, the reading and writing of it inevitably lead to security risks, even if the operation on the local host to be quite cautious, let alone exposure to the number of unpredictable users of the network environment, should be in the public registry read and write operation when cautious! Or, simply find another way to replace!

It is for this reason that asp.net application settings are stored in addition to the registry, and more, in the following two ways:

# application objects

# Web.config file

Use the Application object to store application settings

For us, the application object is quite familiar. It is one of the two objects that ASP.net has retained from the ASP to simplify application state management (the other is the session object). As a asp.net application, Web services can access application objects just like any other Web application.

In ASP.net, a Application object can be considered a global variable in a high-level language. It is consistent in the application to achieve global information sharing between multiple sessions and requests in a asp.net application. (It is important to mention that the ASP.net application is the sum of all files, pages, handlers, modules, and code within a virtual directory and its subdirectories within a single WEB server.) )

Unlike normal global variables, the ASP.net application state Application object is created the first time a client requests any URL resource from a particular asp.net application virtual directory. Each asp.net application on the WEB server creates a separate instance. The reference to each instance is then exposed through this Application object.

This allows the application object to be used to hold data that needs to be shared by different users, documenting the settings of the application so that it can be accessed by all code that runs in the same Web application, and, further, external methods containing the Application object as Web services, To share the object in the application and manipulate the application settings values. The state programming of the number of application accesses, the interop programming to read remote databases, and so on, are shared by the settings of the application in a similar way.

The following code uses the Application object to record the number of accesses to a particular application and to external the method to the Web service for application invocation:

[WebService (namespace= "http://www.thjx.com")]
public class Application:System.Web.Services.WebService
{
<summary>
Returns the number of times an application has been accessed
</summary>
[WebMethod (description= "returns the number of times a particular application has been accessed")]
public int Getappaccesscount (string key)
{
if (application[key]==null)
{
Application.Lock ()//Lock Application object to synchronize Access
Application[key]=1;
Application.UnLock ()//unlock
}
Else
{
Application.Lock ();
Application[key]=int32.parse (Application[key]. ToString ()) +1;
Application.UnLock ();
}
return (int) Application[key];
}
}



Method Getappaccesscount (String key) increments the number of accesses by 1 units after a particular application is executed, and is saved in the application settings variable, and the next time access from any user increments the setting on the basis of that variable.

V. Using web.congfig files to store application settings

As you can see from the above, asp.net applications need to configure a number of special settings, including timeouts for all page settings, custom error pages instead of default IIS error pages, and security settings and authorization level settings. It seems that so many types of settings must be cumbersome, and luckily, ASP.net ends the history of having to manually configure the settings in a Web.config file. This is a different way of saving application settings than the previous mention of using a registry or Application object to save application settings. Because the Web.config file exists in the application root directory, the application settings saved in this manner make the application cross-platform and scalable.

There are many advantages to using Web.config files to store application settings, web.config is actually a plain text file, obviously, configuration information stored in plain text files is very easy to modify, and, unlike traditional ASP, any modifications to configuration settings do not require a restart of the Web server to be applied immediately to the current Web application, and the configured configuration is automatically applied to the current folder and all of its subfolders, making it possible for a truly compatible host to Xcopy, and we only need to replicate all the Web application files in another IIS virtual directory to implement the application deployment; The configuration of some specific tasks, such as form based authorization, can only be achieved by using the Web.config file.

Here, it is necessary to briefly talk about the construction of the Web.config file. The web.config file is a standard XML file that follows all the specifications of the well-formed XML document. It consists of several parts, each part dealing with a special task. The Web.config file consists of a number of subsections, including validation bars, security sections, error handling sections, and Web services sections. and save the application configuration information as a key-value pair.

As a standard XML document, the root element of the Web.config file is <configuration&gt, which contains a child element <system.web&gt, and the latter includes many configuration parts. The Web.config file contains many tags, each of which corresponds to a so-called "section". For example, the authentication that represents authentication, the authorization that represents authorization, the customerrors of custom errors, the session settings sessionstate, and so on.

Although the Web.config file provides a lot of space for user customization, we may still need some user settings. AppSettings part is used to satisfy this requirement, please remember that this part is not in <system.web ></system.web> tag, but is stored separately in <configuration></ In the configuration> tag, the database connection string, email server address, and log files are stored in the path, which can usually be placed in this section.

The following code fragment is a set section of a Web.config file that defines the application settings, the appsettings section, which contains the database connection string and another user set LogFilePath key value pair:

<configuration>
<appSettings>
<add key= "Conn" value= server= (local) uid=sa;pwd=;d atabase=mydb "/>
<add key= "LogFilePath" value= "C:\mylogs"/>
</appSettings>
</configuration>



. NET Framework supports ASP.net application access to application settings. Its ConfigurationSettings class provides access to configuration settings in the specified configuration section. The Public property ConfigurationSettings.AppSettings property of the class can get the configuration settings in the <appSettings> element configuration section, which is a namevaluecollection, It contains the name/value pairs of the configuration settings:

public static namevaluecollection.appsettings {get;}



The following Web service methods are used to obtain application configuration settings: Using System.Configuration;

[WebMethod]
public string getappsetting (string key)
{
return Configurationsettings.appsettings[key];
}



Note that the AppSetting property is read-only and you must edit the Web.config file to modify the application settings. Also, if key key does not exist in the Web.config file, reading the AppSettings property throws an error.

The ConfigurationSettings class also provides a public method configurationsettings.getconfig the configuration settings that are used to return a user-defined configuration section.

public static Object GetConfig (string sectionname);



Where the parameter sectionname represents the configuration section to read. The following Web service method is used to get the specified key value for a user-defined configuration:

[WebMethod]
public string GetConfig (string key)
{
NameValueCollection nv=new NameValueCollection ();
Instantiating a NameValueCollection class object
nv= (NameValueCollection) configurationsettings.getconfig ("appSettings");
Returns the settings for a user-defined configuration section
Return Nv[key]. ToString ();
Returns a specific key value
}



Vi. consuming "Web services for implementing asp.net application Settings"

You can write applications such as Web applications, Windows desktop applications, or Web services to consume the application settings Web services that you have created. Implemented in the same way as any standard Web service, there is nothing special, it should be said very simply, here is not the explanation.

Related Article

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.