The use of WebAPI

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Through these two articles make me understand the simple use of WEB API.

Parry is the use of WebAPI in MVC: Visual Studio 2012 MVC4 project, there is a WebApiConfig.cs file in the App_Start directory, the file is the appropriate Web API routing configuration.

I also according to the two article wrote a simple test program.

First create a UserModel

public class UserModel
{
    public string UserID { get; set; }
    public string UserName { get; set; }
}

Then add Web API Controller

public class UserController : ApiController
{
    public UserModel getAdmin()
    {
        return new UserModel() { UserID = "000", UserName = "Admin" };
    } 
}

The registered route

public static void Register(HttpConfiguration config)
{
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

Registered in Global

protected void Application_Start(object sender, EventArgs e)
{
    WebApiConfig.Register(GlobalConfiguration.Configuration);
}

Access address in the address bar this time: api/user/getadmin

image

This time the default return XML data model.

Use the API AJAX request, specifying the data format for the JSON

$.ajax({
    type: 'GET',
    url: 'api/user/getadmin',
    dataType: 'json',
    success: function (data, textStatus) {
        alert(data.UserID + " | " + data.UserName);
    },
    error: function (xmlHttpRequest, textStatus, errorThrown) {
    }
});

Results alert out of the:

image

So, it is what Dudu says, can according to the request of the data type returns the specified data format.


POST data

Change the controller, add a add method

public bool add(UserModel user)
{
    return user != null;
}

In order to test, so here only to judge whether the incoming entity is empty, if not empty returns true

I added a button on the page, the code as follows:

<input type="button" name="btnOK" id="btnOK" value="Sending a POST request" />

Add the JS code

$('#btnOK').bind('click', function () {
    //To create an Ajax request, sending data to the background processing
    var postData = {
        UserID: '001',
        UserName: 'QeeFee'
    };
    $.ajax({
        type: 'POST',
        url: 'api/user/add',
        data: postData,
        dataType: 'json',
        success: function (data, textStatus) {
            alert(data);
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
        }
    });
});

Run the page again

image

We added process for debugging, when sending a Ajax request, the server receives the data as shown in Figure

image

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Lena at November 13, 2013 - 10:13 AM