ASP 5 Series tutorial (vii) End-interpreting code

Source: Internet
Author: User
Tags naming convention hosting

??

In this article, we'll look at the Todocontroller class code together.

The [Route] property defines the URL template for the controller:

[Route ("Api/[controller]")]

All HTTP requests that conform to the template type are routed to the controller. In this example, the routing naming convention is the prefix of the corresponding controller. For the Todocontroller class. The routing template is "Api/todo".

HTTP method

The [HttpGet],[HttpPost] , and [Httpdelete] properties are defined as the appropriate HTTP method for the controller action (there are also [Httpput] and [Httppatch] property, not used in this demo sample. )

[HttpGet]
 Public Ienumerable<todoitem> GetAll () {}
[HttpGet ("{id:int}", Name = "getbyidroute")]
 Public Iactionresult GetById (int id) {}
[HttpPost]
 public void Createtodoitem ([frombody] TodoItem item) {}
[Httpdelete ("{id:int}")]
 Public Iactionresult DeleteItem (int id) {}

The parameters in the GetById and DeleteItem methods can add routing information. Therefore, the routing template is more well-written as "Api/[controller]/{id:int}".

In "{Id:int}", the ID is a variable. The ": int" represents the integer type. The following is an example of URLs:

Http://localhost/api/todo/1
Http://localhost/api/todo/42

cannot be written as:

Http://localhost/api/todo/abc

Note that the GetById and DeleteItem methods have the same number of parameters named IDs.

The framework will voluntarily pass the actual values to the controller itself. For example, suppose the URL is http://localhost/api/todo/42. The value of the ID is 42, and the process is bound to the parameter.

The Createtodoitem method represents a parameter binding:

[HttpPost]
 public void Createtodoitem ([frombody] TodoItem item) {}

The [Frombody] property specifies that the framework deserializes Todoitem parameters from the request.

The following is a list of request and controller actions:

Request

Controller Action

Get/api/todo

GetAll

Post/api/todo

Createtodoitem

Get/api/todo/1

GetById

Delete/api/todo/1

DeleteItem

Get/api/todo/abc

None–returns 404

Put/api/todo

None–returns 404

The last two examples return 404 errors for other purposes.

For example ' GET/API/TODO/ABC ', ' abc ' is the integer data type required in the GetByID method.

Action return value

The Todocontroller class shows the return value methods for various controller actions.

The GetAll method returns a CLR object.

[HttpGet]
 Public Ienumerable<todoitem> GetAll ()
{
    return _items;
}

The serialized information of the returned object is stored in the response message.

The default format for Json,client is the same as the ability to receive XML data formats:

GET Http://localhost:5000/api/todo http/1.1
User-agent:fiddler
host:localhost:5000
Accept:application/xml

Response:

http/1.1 OK
Content-type:application/xml;charset=utf-8
server:microsoft-httpapi/2.0
Date: Thu, Oct 22:40:10 GMT
content-length:228
<arrayoftodoitem xmlns:i= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "http// Schemas.datacontract.org/2004/07/todoapi.models"><TodoItem><Id>1</Id><IsDone> false</isdone><title>first item</title></todoitem></arrayoftodoitem>

The GetById method returns a Iactionresult interface:

[HttpGet ("{id:int}", Name = "getbyidroute")]
 Public Iactionresult GetById (int id)
{
    var item = _items. FirstOrDefault (x = x.id = = Id);
    if (item = = NULL)
    {
        return Httpnotfound ();
    }
    return New Objectresult (item);
}

If there is a corresponding ID in the URL, this method returns Objectresult. Returns Objectresult and returns the same as the CLR model.

The method specifies that the return type is Iactionresult. Therefore, the method can return different types.

If there is no corresponding ID, the Httpnotfound is returned. The page will throw a 404 error.

Finally, the Createtodoitem method shows how to set the return value directly in the method:

[HttpPost]
 public void Createtodoitem ([frombody] TodoItem Item)
{
     not shown here)
    Context.Response.StatusCode = 201;
    context.response.headers["location"] = URL;
}

The flaw in such a method is that it is very difficult to test the unit. (For a test-related discussion, you can refer to the unit testing Controllers in ASP.)

Dependency Injection

MVC 6 has built-in dependency injection capabilities.

Below, let's create a repository class that includes a todo list.

First of all. Define an interface for repository:

using System.Collections.Generic;
namespace Todoapi.models
{
     Public Interface Itodorepository
    {
        get; }
        void Add (TodoItem item);
        TodoItem GetById (int id);
        BOOL Trydelete (int id);
    }
}

The detailed implementation method is then defined.

using System;
using System.Collections.Generic;
using System.Linq;
namespace Todoapi.models
{
     Public class Todorepository:itodorepository
    {
        ReadOnly New List<todoitem> ();
         Public Ienumerable<todoitem> AllItems
        {
            Get
            {
                return _items;
            }
        }
         Public TodoItem GetById (int id)
        {
            return _items. FirstOrDefault (x = x.id = = Id);
        }
         public void Add (TodoItem item)
        {
            Item. Id = 1 + _items. Max (x = (int?) x.id)?

? 0;

            _items. ADD (item);
        }
         public bool Trydelete (int id)
        {
            var item = GetById (ID);
            if (item = = NULL)
            {
                return false;
            }
            _items. Remove (item);
            return true;
        }
    }

Use the constructor to inject repository to the controller:

[Route ("Api/[controller]")]
 Public class Todocontroller:controller
{
    Remove This code:
    staticreadonlynew list<todoitem> ()
    //{
        New TodoItem {Id = 1, Title = "FirstItem"}
    //};
    ADD This code:
    Private ReadOnly Itodorepository _repository;
     Public Todocontroller (Itodorepository repository)
    {
        _repository = repository;
    }

Then update the Controller method to repository:

[HttpGet]
 Public Ienumerable<todoitem> GetAll ()
{
    return _repository. AllItems;
}
[HttpGet ("{id:int}", Name = "getbyidroute")]
 Public Iactionresult GetById (int id)
{
    var item = _repository. GetById (ID);
    if (item = = NULL)
    {
        return Httpnotfound ();
    }
    return New Objectresult (item);
}
[HttpPost]
 public void Createtodoitem ([frombody] TodoItem Item)
{
    if (! Modelstate.isvalid)
    {
        Context.Response.StatusCode = 400;
    }
    Else
    {
        _repository. ADD (item);
        string url = Url.routeurl ("getbyidroutenew {id = Item. Id}, Request.scheme, Request.Host.ToUriComponent ());
        Context.Response.StatusCode = 201;
        context.response.headers["location"] = URL;
    }
}
[Httpdelete ("{ID}")]
 Public Iactionresult DeleteItem (int id)
{
    if (_repository. Trydelete (ID))
    {
        return New Httpstatuscoderesult (204); 201 No Content
    }
    Else
    {
        return Httpnotfound ();
    }
}

We need to register repository to rely on the injection system talents to make it work.

In the Startup class. Add the following code:

 public void configureservices (iservicecollection services)
{
    Services. Addmvc ();
    New Code
    Services. Addsingleton<itodorepository, todorepository> ();
}

When the application executes, once the controller is created. The framework itself injects todorepository into a controller, which acts on the entire application lifecycle.

Standalone deployment of apps outside of IIS

By default, when you click F5, the app is executed in IIS Express. You can see the IIS Express icon in the toolbar.

The ASP. NET 5.0 can be deployed to different servers, and in this section we will use Weblistener that are executable outside of IIS.

Note: There are still many advantages to deploying your app in IIS, such as security, progress management, and so on.

In the Project.json file. Add Microsoft.AspNet.Server.WebListener Package:

"dependencies": {
    "Microsoft.AspNet.Server.IIS": "1.0.0-beta1",
    "Microsoft.AspNet.Diagnostics": "1.0.0-beta1",
    "Microsoft.AspNet.Mvc": "6.0.0-beta1",
    New:
    "Microsoft.AspNet.Server.WebListener": "6.0.0-beta1"
},

Next, add the following option to Project.json.

{
    Other sections not shown
    "Commands": {
        "": "Microsoft.AspNet.Hosting--server Microsoft.AspNet.Server.WebListener--server.urls/http// localhost:5000"
    }
}

The "commands" includes a list of pre-defined directives that can be passed to K execution. In this example. "Web" is the directive name. It can be a random actual instruction name value.

The Microsoft.AspNet.Hosting assembly is used to deploy ASP. NET 5.0 applications.

· The--server tag is used to declare the server, which in this example is Weblistener.

· The--server.urls tag provides a URL that needs to be monitored.

Save the Project.json file.

In Solution Explorer, right-click the project to select Properties. In the Properties Bar, click Debug. Under Debug target . Change "IIS Express" to "web".

Click F5 to execute the app. Visual Studio then executes the console app that starts Weblistener.

Open the browser and enter http://localhost:5000.

You can see the Welcome screen.

Suppose you need to use IIS. You can change the debug Target to "IIS Express" in the previous step.

This article is the last article in this series, thank you for your attention. All the tutorials in this series are designed to help you understand ASP. NET 5. For better development. At the same time, some development tools are available to help with the development process.

ComponentOne Studio for ASP . NET platform for Creating and designing modern-style Web applications in a variety of browsers.

Original link: http://www.asp.net/vnext/overview/aspnet-vnext/create-a-web-api-with-mvc-6

Folder:
    • ASP. 5 Series Tutorial (i): bribed new features
    • ASP. 5 Series Tutorial (ii): Hello World
    • ASP 5 Series Tutorial (iii): View Components Introduction
    • ASP. NET 5 Series tutorial (iv): adding services to a view and publishing apps to the public cloud
    • ASP. NET 5 Series tutorial (V): Developing Web Programs using Grunt, bower in Visual Studio 2015
    • ASP. NET 5 Series tutorial (vi): Creating a Web API in MVC6
    • ASP 5 Series tutorial (vii) End-interpreting code

ASP 5 Series tutorial (vii) End-interpreting code

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.