There are two reasons for choosing ASP. net mvc: 1. Compile Web ProgrammingProgramThis sentence may sound a bit open, but it will be obvious compared with webform. In order to simulate winform, webpage sacrifices too many web features, these features are key to HTTP. ASP. net MVC is very convenient to build Web Services. Why? Basically, every action of ASP. net mvc is like an httphandler. It can process various types of requests, and the use of controller and fitler makesCodeThe organization and function expansion have been greatly improved. As you can say, the M $ framework is more suitable for MVC than Silverlight, I think there is no right choice for learning MVC.
Using WCF can also build restful services, but even WCF cannot claim that it is a restful framework. What programming experience does it talk about? Instead, it builds RPC-based Web Services, this is not what I want to do for a long time. When I sorted out the materials yesterday, I found a paragraph in the previous document. I would like to summarize the methods of RPC and Roa:
- RPC (Remote Procedure Call) architecture uses the SOAP protocol, uses various contracts, and is highly dependent on development tools.
- Roa (Resource Oriented Architecture) is a resource-oriented architecture that uses the HTTP protocol directly and uses a unified interface that is similar to the original web development method.
- The RPC architecture has many layers of packaging, and has low interoperability and scalability and maintainability.
- Roa-based architecture access is transparent, and all services adopt the same access method.
- RPC architecture exposed internallyAlgorithm.
- The RoA architecture exposes internal data.
- RPC architecture is process-oriented.
- Roa architecture can be object-oriented
The topic about the restful service is not the focus of today's discussion. If you are interested, you can view the restful blog in your blog or read the book restful web service, that book is good, but it is suitable for reading in leisure time. If the project is in urgent need of use, it will not be necessary.
Prepare to use ASP. net MVC programming, Asp. net MVC has an understanding of all aspects. Otherwise, if the project is half done and suddenly finds that there is a detour, it will be too much trouble. In the past two days, I tried to use MVC to do something, today, I will try again to explain how to use the MVC framework to build a restful service.
I have always been an enterprise information management system. Therefore, the technology mentioned in general is a solution for architecture and Implementation of the enterprise information management system. If you are a web application, there may be differences in thinking.
In my ideas, for an enterprise information management system, a basic service (such as account management) is simply used to manage data through pages, then, you can use the service method to publish data. Simply put, you can create a project. There are two parts: one is the add, delete, modify, and query page, and the other is the data service called by other systems, this design can reduce the complexity at the early stage of the system architecture, namely: first design a read-only service, and then extend it to a read-write service after the application is extended to a certain extent. In MVC, there is an "area" method. I feel that we can isolate websites and services from the code perspective. Of course, it is also feasible to build two applications, however, if the application scale is not large enough, it is not a bad thing to simplify the structure.
The first step after creating an MVC project is to consider the access permission issue. There is certainly no error in controlling the permissions using SSO in the page section, if it is only a system call from your own company, it is feasible to use SSO authentication. You only need to add the formsauthentication ticket in future requests. if the service needs to be made an open application, so using oauth is a good choice, but this solution seems a little too heavyweight. The next method uses HTTP basick authentication, and of course SSO authorization can also be used as needed.
Because we are building a Test Service, the Access Authorization issue can be left blank. However, if you are working on a project, there is only one piece of advice: The sooner the Access Authorization issue is considered, the better.
Create an ASP. as a service provider, the MVC project creates an area named "SVC" and creates a new controller named usercontroller in the Controller folder. The internal code is as follows:
Public class usercontroller: controller {private const string outerns = "http://sample.cleversoft.com/user/1.0"; Public actionresult getall () {actionresult result = NULL; var users = This. getusers (); If (this. controllercontext. httpcontext. request. contenttype. contains ("application/atom + XML") {var feed = new syndicationfeed (); var items = new list <syndicationitem> (); foreach (VAR user in users) {var item = new syndicationitem (); item. id = user. id. tostring (); item. title = new textsyndicationcontent (user. name); item. elementextensions. add ("name", outerns, user. name); item. elementextensions. add ("mail", outerns, user. mail); items. add (item);} feed. items = items; Result = new syndicationfeedresult (feed);} else {var JSON = new jsonresult (); JSON. jsonrequestbehavior = jsonrequestbehavior. allowget; JSON. data = (from user in users select new {id = user. id. tostring (), name = user. name, mail = user. mail }). toarray <Object> (); Result = JSON;} return result;} private ilist <user> getusers () {var users = new list <user> (); users. addrange (new user [] {new user () {id = guid. newguid (), name = "A", password = "A", mail = "a@cleversoft.com"}, new user () {id = guid. newguid (), name = "B", password = "B", mail = "B @cleversoft.com"}, new user () {id = guid. newguid (), name = "C", password = "C", mail = "c@cleversoft.com"}, new user () {id = guid. newguid (), name = "D", password = "D", mail = "d@cleversoft.com"}, new user () {id = guid. newguid (), name = "E", password = "E", mail = "e@cleversoft.com"}); Return users ;}} public class user {public guid ID {Get; set;} public string name {Get; set;} Public String password {Get; set;} Public String mail {Get; Set ;}}
Because not every user calls it through the client, I provide two data response formats for a service. If the Content-Type of the request isIf application/atom + XML is used, data is returned in atom format; otherwise, data in JSON format is returned. The syndicationfeedresult type is defined here.
Create another project as the client for testing the service, and add the following code to the project as the client for the service:
Public class client {public syndicationfeed query (URI queryuri) {var request = webrequest. createdefault (queryuri); Request. method = "get"; request. contenttype = "application/atom + XML, charset = \" UTF-8 \ ""; // authorization var response = request. getresponse () as httpwebresponse; var stream = response. getresponsestream (); var feed = syndicationfeed. load <genericfeed <user> (xmlreader. create (Stream); stream. close (); response. close (); Return Feed;} public class genericfeed <t>: syndicationfeed where T: syndicationitem, new () {protected override syndicationitem createitem () {return New T () ;}} public class user: syndicationitem {private const string outerns = "http://sample.cleversoft.com/user/1.0 "; public string name {get {return getvalue <string> ("name") ;}set {setvalue ("name", value );}} public String mail {get {return getvalue <string> ("mail") ;}set {setvalue ("mail", value );}} private t getvalue <t> (string outername) {return base. elementextensions. readelementextensions <t> (outername, outerns) [0];} private void setvalue (string outername, object Value) {base. elementextensions. add (outername, outerns, value) ;}} public class usermanager {public ilist <user> getall () {// get service url uri queryuri = new uri ("http: // localhost: 20074/svc/user/getall/"); var client = new client (); var feed = client. query (queryuri); var result = (from item in feed. items select item as user ). tolist <user> (); return result ;}}
Then, call the client
Public class homecontroller: controller {public actionresult index () {viewbag. Message = "Welcome to ASP. net mvc! "; Usermanager = new usermanager (); var users = usermanager. getall (); Return view (users) ;}public actionresult about () {return view ();}}
The corresponding view is as follows:
@ Model ilist <restfulclient. code. user >@{ viewbag. title = "home page" ;}< H2> @ viewbag. message </H2> <p> to learn more about ASP. net MVC visit <a href = "http://asp.net/mvc" Title = "ASP. net MVC Website "> http://asp.net/mvc </a>. </P> <Table> <tr> <TD style = "width: 200px"> id </TD> <TD style = "width: 200px "> name </TD> <TD style =" width: 200px "> mail </TD> </tr> @ foreach (VAR user in Model) {<tr> <TD> @ user. id. tostring () </TD> <TD> @ user. name </TD> <TD> @ user. mail </TD> </TR >}</table>
The F5 running result is as follows:
The above are my initial ideas and practices for building a restful service using MVC. There are certainly many details to consider in the real application. You are welcome to share your thoughts and suggestions.
Sample program
Updated on April 9, March 25: Post syndicationfeed example -----------------------------------
Server:
[Httppost] public actionresult create () {If (request. contenttype. toupper (). startswith ("application/atom + XML ". toupper () {syndicationfeed = syndicationfeed. load (xmlreader. create (request. inputstream);} return New emptyresult ();}
Client:
Public void create (URI posturl, genericfeed
feed) {var request = webrequest. createdefault (posturl); Request. method = "Post"; memorystream MS = new memorystream (); Using (VAR writer = xmlwriter. create (MS) {feed. saveasatom10 (writer);} request. contenttype = "application/atom + XML"; request. contentlength = Ms. length; using (VAR Sw = request. getrequeststream () {SW. write (Ms. toarray (), 0, (INT) ms. length);} var response = request. getresponse (); // todo ...}