MVC4 WebAPI (i) (EXT)

Source: Internet
Author: User

Source: http://www.cnblogs.com/wk1234/archive/2012/04/28/2468491.html

For whatever reason, the result is that in the new MVC, the WEBAPI is added to provide restful webservice, and the individual prefers restful webservice, feeling lighter than soap and less demanding on the client, More in line with the general mode of network data transmission, the client completely out of the agents and pipelines to interact directly with WebService, the specific differences can be found in Web services programming, REST and SOAP

(i) Environmental preparedness

The environment of the machine is xp+vs2010, need to install VS2010 SP1 upgrade package, MVC4 upgrade package, Vs2010 install SP1 will affect the SQLServer2008 automatic prompt function, need to install patches or plug-ins, after successful installation can create the following MVC WebAPI Project

(ii) overview

The newly generated WEBAPI project, like a typical MVC project, contains the main models,views,controllers folders and Global.asax files


Views are not very useful for WEBAPI, the model in models is primarily used to hold the objects of service and client interaction, which by default are converted to JSON-formatted data for transmission. The controller in controllers corresponds to WebService as a resource for service delivery. Like normal MVC, Global.asax is used to configure routing rules

(c) Models

In stark contrast to the data contract in WCF, the model in MVC Webapi is simple poco, and there is nothing else like, you can create the following model

    public class Testusemode    {public        string Modekey{get;set;}        public string Modevalue {get; set;}            }

Note: Model must provide a property of public for assignment when JSON or XML is deserialized

(d) Controllers

The controllers in MVC Webapi is similar to the controllers of normal MVC, but no longer inherits from the controller, but instead inherits the Apicontroller of the API, a controller can contain more than one action, These action response requests are related to the routing rules configured in global, and are explained at the end of the global

(v) Global

By default, the template comes with two routing rules that correspond to Web requests for Webapi and normal MVC, and the default Webapi routing rules are as follows

1             routes. Maphttproute (2                 Name: "Defaultapi", 3                 routetemplate: "Api/{controller}/{id}", 4                 defaults:new {id = Routeparameter.optional}5             );

As you can see, the default route uses a fixed API as the forerunner of the URI, which, according to Microsoft's official parlance, is used to differentiate between normal Web requests and WebService request paths:

Note: The reason for using ' API ' in the ' route is ' to ' avoid collisions with ASP. NET MVC routing. That's the, you can have the "/contacts" go to an MVC controller, and the "/api/contacts" go to a WEB API controller. Of course, if you don't like this convention, you can change the default route table.

As you can see, the default routing rule only points to the controller and does not point to the specific action because, by default, the match for the action in the controller is associated with the action's method name:

Specifically, if you use the routing rules above, the following controller is appropriate:

    public class Testcontroller:apicontroller {public static list<testusemode> allmodelist = new LIST&L T        Testusemode> ();        Public ienumerable<testusemode> GetAll () {return allmodelist; } Public ienumerable<testusemode> GetOne (string key) {return Allmodelist.findall (mode) =& Gt {if (mode. Modekey.equals (key)) return true; return false;        });            } public bool Postnew (Testusemode mode) {Allmodelist.add (mode);        return true; } public int Delete (string key) {return Allmodelist.removeall (mode) + = {if (mode. Modekey = = key) return true; return false;        });        } public int DeleteAll () {return Allmodelist.removeall (mode) = = {return true;}); The public int putone (string key, String value) {list<testusemode> updatalist = allmodelist. FindAll (Mode) = {if (mode. Modekey = = key) return true; return false;            }); foreach (var mode in updatalist) {mode.            Modevalue = value;        } return Updatalist.count; }    }

Then, there is a corresponding relationship:

Simply use JS to invoke the data interface provided above

 1 function GetAll () {2 $.ajax ({3 URL: "api/test/", 4 type: ' GET ', 5 Success:function (data) {6 document.getElementById ("Modes"). InnerHTML = ""; 7 $.each (data, function (key, Val) {8 var str = val). Modekey + ': ' + val. Modevalue;                 9 $ (' <li/> ', {html:str}). AppendTo ($ (' #modes ')); 10}); 11             }12}). Fail (XHR, Textstatus, err) {+ alert (' Error: ' + err); 15 });}17 function Add () {$.ajax ({api/test/URL: " , type: "POST", DataType: "JSON", data: {"Modekey": Document.getele Mentbyid ("Txtkey"). Value, "Modevalue": document.getElementById ("Txtvalue"). Value},27 Success:function (d                ATA) {28     GetAll ();}30}). Fail (XHR, Textstatus, err) {32 Alert (' Error: ' + err ');}36 PNs function Find () {$.A                 Jax ({url: "api/test/" + document.getElementById ("Txtfindkey"). Value,41 type: ' GET ', 42                     Success:function (data) {document.getElementById ("modes"). InnerHTML = ""; 44 $.each (data, function (key, Val) {var str = val. Modekey + ': ' + val.                 modevalue;46 $ (' <li/> ', {html:str}). AppendTo ($ (' #modes ')); 47}); 48  }49}). Fail (function (XHR, textstatus, err) {(' Error: ' + ERR);}54 RemoveAll () {$.ajax ({. URL: "AP i/test/", the type: ' DELete ', success:function (data) {document.getElementById ("modes"). InnerHTML = ""; GetAll ();}63}). Fail (XHR, textstatus, err) {+ alert (' Error: ' + err); 66}); }68-Function Remove () {$.ajax ({api/test/URL: "+document.getelemen")                     Tbyid ("Txtremovekey"). Value,72 type: ' DELETE ', success:function (data) {74             document.getElementById ("Modes"). InnerHTML = ""; GetAll (); 76}77         }). Fail (XHR, Textstatus, err) {+ alert (' Error: ' + err); 80}); 81 }82 Update () {$.ajax ({$ URL: "api/test/", type : ' PUT ', DataType: "JSON", data: {"key": documenT.getelementbyid ("Txtupdatekey"). Value, "value": document.getElementById ("Txtupdatevalue"). Value},89 succ Ess:function (data) {document.getElementById ("modes"). InnerHTML = ""; getAll ();}93}). Fail (94 function (XHR, textstatus, err) { ROR: ' + err); 96}); 97}

This enables the most basic crud operations.

(vi) Routing rule extension

Like normal MVC, MVC WEBAPI supports custom routing rules, such as: In the above operation, the routing rules use

"Api/{controller}/{id}"

When using the Get method to pass the value of the URL, the receiver parameter named ID, but in the controller, the GetOne method receives the parameter named key, is not matched, this is only need to add a new routing rule, or modify the original routing rule to:

"Api/{controller}/{key}"

Of course, you can extend the route further, such as: extending to the same route as normal MVC:

"Api/{controller}/{action}/{id}"

This requires that both the action and HTTP methods be used to match
Of course, according to Microsoft, this use is not recommended, because it does not meet the general perception of WebService:

For a RESTful API, you should avoid using verbs in the URIs, because a URI should identify a resource, not an action.

(vii) using attribute to declare HTTP methods

Does it feel silly to use the default method name to match HTTP method? Or I have some ways to use it, do not want to expose, and what to do? It's also nice to use attribute to do these things, like the action I can change to:

        [HttpGet]        Public ienumerable<testusemode> FindAll ()        [httpget] public        ienumerable<testusemode> Findbykey ( String key)        [HttpPost] public        bool Add (testusemode mode)        [httpdelete] public        int Removebykey (string Key)        [httpdelete] public        int RemoveAll ()        [httpput] public        int Updatebykey (string key, String value )       [nonaction] public         string GetPrivateData ()

Of course, I only listed the method names, not these methods really no method body ... The method body is immutable, and noaction indicates that the method does not receive the request, even if it starts with get.
If you feel that regular get,post,delete,put is not enough, you can also use Acceptverbs to declare HTTP methods, such as:

        [Acceptverbs ("Mkcol", "HEAD")]        public int Updatebykey (string key, String value)        {            list<testusemode> updatalist = Allmodelist.findall ( mode) = = {if (mode. Modekey = = key) return true; return false; });            foreach (var mode in updatalist)            {                mode. Modevalue = value;            }            return updatalist.count;        }

******************************************************************************
Wang Kun
Source: http://www.cnblogs.com/wk1234
This article is copyright Wang Kun and blog garden altogether, welcome reprint, but please indicate the source.

MVC4 WebAPI (i) (EXT)

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.