MVC4 WebAPI (1), mvc4webapi

Source: Internet
Author: User

MVC4 WebAPI (1), mvc4webapi
MVC4 WebAPI (1)

No matter what the reason is, the result is added to the new MVC, WebAPI is used to provide REST-style WebService. I personally prefer REST-style WebService, and it feels lighter than SOAP, in addition, the client has fewer requirements and is more in line with the general network data transmission mode. The client can directly interact with WebService without proxy and pipeline. For specific differences, see Web Service programming, REST and SOAP

(1) Prepare the environment

The local environment is XP + VS2010. You need to install the VS2010 SP1 upgrade package and the MVC4 upgrade package. After installing SP1 in Vs2010, the automatic prompt function of SQLServer2008 will be affected. You need to install patches or plug-ins, after successful installation, you can create the following MVC WebAPI project:

(2) Overview

The newly generated WebAPI project is the same as the typical MVC project, including the main Models, Views, Controllers and other folders and Global. asax files.


Views is not very useful for webapis. The Model in Models is mainly used to save the objects that the Service and Client interact with. By default, these objects are converted to Json format for data transmission, the Controller in Controllers is a Resource corresponding to WebService and is used to provide services. Like common MVC, Global. asax is used to configure routing rules.

(3) Models

In stark contrast to the data contract in WCF, the Model in MVC WebAPI is a simple POCO, and there is nothing else, for example, you can create the following Model

    public class TestUseMode    {        public string ModeKey{get;set;}        public string ModeValue { get; set; }            }

Note: The Model must provide the public attribute for the value assignment during json or xml deserialization.

(4) Controllers

Controllers in MVC WebAPI is similar to Controllers in common MVC, but does not inherit from Controller. Instead, it inherits the API's ApiController. A Controller can contain multiple actions, the methods for responding to these actions are related to the routing rules configured in Global.

(5) Global

By default, the template comes with two routing rules, which correspond to Web requests of WebAPI and common MVC respectively. The default routing rules of WebAPI 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 Uri pilot. According to Microsoft's official statement, it is used to differentiate the request paths of common Web requests and WebServices:

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

You can see that the default routing rule only points to the Controller, but not to the specific Action, because by default, the Action matching in the Controller is associated with the Action Method Name:

Specifically, if the preceding routing rules are used, they correspond to the following Controller:

    public class TestController : ApiController    {        public static List<TestUseMode> allModeList = new List<TestUseMode>();        public IEnumerable<TestUseMode> GetAll()        {            return allModeList;        }        public IEnumerable<TestUseMode> GetOne(string key)        {            return allModeList.FindAll((mode) => { 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; });        }        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 will be the following correspondence:

Use JS to call 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(13             function (xhr, textStatus, err) {14                 alert('Error: ' + err);15             });16         }17 18 19 20         function add() {21 22             $.ajax({23                 url: "api/Test/",24                 type: "POST",25                 dataType: "json",26                 data: { "ModeKey": document.getElementById("txtKey").value, "ModeValue": document.getElementById("txtValue").value },27                 success: function (data) {28                     getAll();29                 }30             }).fail(31             function (xhr, textStatus, err) {32                 alert('Error: ' + err);33             });34 35         }36 37         function find() {38             39             $.ajax({40                 url: "api/Test/" + document.getElementById("txtFindKey").value,41                 type: 'GET',42                 success: function (data) {43                     document.getElementById("modes").innerHTML = "";44                     $.each(data, function (key, val) {45                         var str = val.ModeKey + ': ' + val.ModeValue;46                         $('<li/>', { html: str }).appendTo($('#modes'));47                     });48                 }49             }).fail(50             function (xhr, textStatus, err) {51                 alert('Error: ' + err);52             });53         }54 55         function removeAll() {56             $.ajax({57                 url: "api/Test/",58                 type: 'DELETE',59                 success: function (data) {60                     document.getElementById("modes").innerHTML = "";61                     getAll();62                 }63             }).fail(64             function (xhr, textStatus, err) {65                 alert('Error: ' + err);66             });67         }68 69         function remove() {70             $.ajax({71                 url: "api/Test/"+document.getElementById("txtRemoveKey").value,72                 type: 'DELETE',73                 success: function (data) {74                     document.getElementById("modes").innerHTML = "";75                     getAll();76                 }77             }).fail(78             function (xhr, textStatus, err) {79                 alert('Error: ' + err);80             });81         }82 83         function update() {84             $.ajax({85                 url: "api/Test/",86                 type: 'PUT',87                 dataType: "json",88                 data: { "key": document.getElementById("txtUpdateKey").value, "value": document.getElementById("txtUpdateValue").value },89                 success: function (data) {90                     document.getElementById("modes").innerHTML = "";91                     getAll();92                 }93             }).fail(94             function (xhr, textStatus, err) {95                 alert('Error: ' + err);96             });97         }

In this way, the most basic CRUD operations are implemented.

(6) routing rule Extension

Like common MVC, MVC WebAPI supports custom routing rules. For example, in the preceding operation

"api/{controller}/{id}"

When the GET method is used to transmit values through URLs, the receiving parameter name after the controller is id. However, in the Controller, the receiving Parameter Name of the GetOne method is key and will not be matched, you only need to add a new routing rule or modify the original routing rule as follows:

"api/{controller}/{key}"

Of course, you can perform more in-depth routing expansion, such as routing that is the same as common MVC:

"api/{controller}/{action}/{id}"

In this way, both Action and HTTP must be used for matching.
Of course, according to Microsoft, such use is not recommended, because it does not conform to the general knowledge of WebService:

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

(7) use Attribute to declare the HTTP Method

Is it silly to use the default Method name to match the HTTP Method ?? Or What should I do if I don't want to expose it myself? I still feel more elegant when using attribute to do this work. For example, the above Action can be changed:

        [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 list the method names, but these methods do not actually have a method body. The method body remains unchanged. NoAction indicates that this method does not receive requests, even if it starts with GET.
If the conventional GET, POST, DELETE, and PUT methods are not enough, you can use the AcceptVerbs method to declare the HTTP method, for example:

        [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;        }

**************************************** **************************************
Author: Wang Kun
Source: http://www.cnblogs.com/wk1234
This article is copyrighted by Wang Kun and the blog Park. You are welcome to reprint it, but please indicate the source.

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.