C #3.5 simple website with wcf rest Architecture

Source: Internet
Author: User

Preface

In the past, on Microsoft's platform, a website was constructed, which requires the close combination of traditional database processing code, business logic layer code, front-end page processing, and interactive program processing, it can be said that decoupling is difficult. Website development is difficult, and the update cost is also high. In my experience, a simple website must be a scalable, cross-platform data reuse, and easy-to-maintain architecture. Here I will introduce the architecture I use: database + REST Server + WEB (MVC ?) In the following text, I try to describe the details as little as possible. Just share my current practices with you.

Download example

Summary

On the MS Platform, the database is MS SQL2008. NET3.5 + VS2008: first create a data model, then generate DataContext (database processing layer), then use WCF to generate a REST-style Web Service, and then use Web Service on the website for page processing, the corresponding dynamic website data interaction, you can consider using MSMQ for messages in the future, and then asynchronously care about the Web Service Cache, etc. This is a post, and you will have the opportunity to communicate with you in the future.

I. Database Operations

I often used the factory model before, and later found that large and medium-sized websites basically do not use that complex logic, because the database architecture is basically unchanged, therefore, I directly use C #3.5 Dlinq to achieve higher efficiency and maintenance costs than the traditional c #2.0 approach.

OK. Use VS2008 To create a project DbDomain, create a new Linq To SQL class, connect To the database in the server resource manager, locate the table, and drag it. OK. The specific code is included in the attachment. The database structure is:

The preceding two simple tables are: Member table and article table.
After directly modifying the database, follow these steps. The corresponding * DataContext files are basically in a fixed format. If you are interested, you can study them in depth.

 

Ii. Generate RSET-style Web Services

Why do we need Web services? reuse, caching, EVENT notifications between data, debugging and maintenance, etc. As for why do we need to generate a REST style, Please consciously GG if you don't understand it, of course, not every method is implemented in the REST style. For a relatively high security level, I will still use the traditional generated wsdl web service to arrange the design. These are not considered at the moment.

Create a new wcf application WcfService and create a wcf Service Member. svc. In this example, only simple query and entry of members are implemented: first, let's look at the implementation of IMember:


Namespace WcfService
{
// Note: If you change the Interface Name "IMember", you must also update the reference to "IMember" in Web. config.
[ServiceContract]
Public interface IMember
{
[OperationContract]
[WebGet (UriTemplate = "User/{id}", ResponseFormat = WebMessageFormat. Json)]
User GetUser (string id );
[OperationContract]
[WebInvoke (UriTemplate = "User/{name}/{password}", ResponseFormat = WebMessageFormat. Xml, Method = "POST")]
Int AddUser (string name, string password );


}
}
Note that the first line mark [ServiceContract] is a convertible Service, and 3.5 is mostly in this mode. Next is the [OperationContract] operation method, which is equivalent to the asmx annotation similar to webmethod, then [WebGet (UriTemplate = "User/{id}", ResponseFormat = WebMessageFormat. json)] This indicates the access path and the corresponding format. We expect to access http: // localhost/member. svc/User/1 in the application to support User data in Json format. Here, the User does not have the Member of data, because of the sensitive data control, cache and other considerations, there is a layer in the middle, dedicated cross-platform Interaction:


[DataContract]
Public class User
{
[DataMember]
Public int Id {get; set ;}
[DataMember]
Public string Name {get; set ;}

}
It is very convenient to query in dlinq, for example, look at the specific implementation:


[AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. Allowed)]
Public class Member: IMember
{
Public User GetUser (string id)
{
DbDomain. TestDbHandlerDataContext dc = new DbDomain. TestDbHandlerDataContext ();
Return (from x in dc. member where x. id. toString (). equals (id) select new User {Id = x. id, Name = x. name }). firstOrDefault ();
}
Public int AddUser (string name, string password)
{
If (string. IsNullOrEmpty (name) | string. IsNullOrEmpty (password) return-1;
DbDomain. TestDbHandlerDataContext dc = new DbDomain. TestDbHandlerDataContext ();
DbDomain. Member clsMember = new DbDomain. Member ();
ClsMember. Name = name;
ClsMember. Password = password;
Dc. Member. InsertOnSubmit (clsMember );
Dc. SubmitChanges ();
Return clsMember. Id;
}

}
Note that the first sentence [AspNetCompatibilityRequirements (RequirementsMode = AspNetCompatibilityRequirementsMode. Allowed)] indicates that the service is accessed in IIS. I did not perform cache and so on here. I directly operate the database. Before dlinq operates the data, a DbDomain. TestDbHandlerDataContext dc = new DbDomain. TestDbHandlerDataContext (); query class will be created. Both query and update are required, and the syntax is also standard-Standard. native SQL or dataset will not appear at all. All of these are model object processing. In other words, DataContext should pay attention to using new each time, do not use static.

Note: To make your svc restful, you must modify the annotation of svc in addition to the UriTemplate mentioned above:

Factory = "System. ServiceModel. Activation. WebServiceHostFactory"
Modify web. Config. Note that the following sentence is added to the <system. serviceModel> node:

<ServiceHostingEnvironment aspNetCompatibilityEnabled = "true"/>
In

<Behaviors>
<EndpointBehaviors>
<Behavior name = "RestMemberServiceBehavior">
<WebHttp/>
</Behavior>
</EndpointBehaviors>
Pay attention to the bold and red areas. Pay attention to these points. For more information, see the configuration of my example.
 

 

Then, access http: // localhost: 3274/Member. svc/User/1, and then return data in json format:

The method for adding a database is POST:

Var usern = client. UploadString ("http: // localhost: 3274/Member. svc/User/admin", "POST", String. Empty );
 

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.