ASP. NET 5 Series tutorials (7)-interpreting code

Source: Internet
Author: User

ASP. NET 5 Series tutorials (7)-interpreting code

In this article, we will view the TodoController class code together.

[Route]The property defines the Controller URL template:

[Route(api/[controller])]

 

All HTTP requests that meet 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

[HttpGet],[HttpPost]And[HttpDelete]The attribute is defined as the HTTP method corresponding to the controller action.[HttpPut]And[HttpPatch]Attribute, which is not used in this example .)

[HttpGet]
public IEnumerable
 
   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) {}

 

Parameters in the GetById and DeleteItem methods can add route transmission information. Therefore, the routing template is better written as "api/[controller]/{id: int }".

In "{id: int}", id is a variable, and ": int" indicates that the parameter is an integer. The following is an URLs instance:

http://localhost/api/todo/1
http://localhost/api/todo/42

It cannot be written as follows:

http://localhost/api/todo/abc

 

Note that the GetById and DeleteItem methods also have parameters named as id. Framework automatically passes the real parameter value to the Controller. For example, if the URL is http: // localhost/api/todo/42 and the id value is 42, this process is used to bind the parameter.

The CreateTodoItem method represents another parameter binding:

[HttpPost]
public void CreateTodoItem([FromBody] TodoItem item) {}

 

[FromBody]The attribute specifies that the framework deserializes the TodoItem parameter 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

In the last two examples, Error 404 is returned for other purposes. For example, 'Get/api/todo/abc' and 'abc' are the integer data types required by the GetById method.

Action Return Value

The TodoController class shows the return value methods of multiple controller actions.

The GetAll method returns a CLR object.

[HttpGet]
public IEnumerable
 
   GetAll()
 
{
    return _items;
}

The returned Object serialization information is stored in the Response Message. The default format is JSON. The client can receive XML data in the same format:

GET http://localhost:5000/api/todo HTTP/1.1
 
User-Agent: Fiddler
 
Host: localhost:5000
 
Accept: application/xml

Response:

HTTP/1.1 200 OK
Content-Type: application/xml;charset=utf-8
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 30 Oct 2014 22:40:10 GMT
Content-Length: 228
 
 
  
   1
  
  
   false
  
  
 

 

The GetById method returns an 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 will return ObjectResult. The returned ObjectResult is the same as the returned CLR model. The return type specified in the method is IActionResult. Therefore, this method can return different types.

If no corresponding ID exists, HttpNotFound is returned, and the page will throw the 404 error.

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

[HttpPost]
public void CreateTodoItem([FromBody] TodoItem item)
{
    // (some code not shown here)
 
    Context.Response.StatusCode = 201;
    Context.Response.Headers[Location] = url;
}

 

The disadvantage of this method is that it is difficult to perform unit tests. (For more information about the test, see Unit Testing Controllers in ASP. NET Web API ).

Dependency Injection

MVC 6 has the built-in dependency injection function. Next, let's create a repository class that contains the ToDo list.

First, define an interface for repository:

using System.Collections.Generic;
 
namespace TodoApi.Models
{
    public interface ITodoRepository
    {
        IEnumerable
 
   AllItems { get; }
 
        void Add(TodoItem item);
        TodoItem GetById(int id);
        bool TryDelete(int id);
    }
}

 

Then define the specific implementation method.

using System;
using System.Collections.Generic;
using System.Linq;
 
namespace TodoApi.Models
{
    public class TodoRepository : ITodoRepository
    {
        readonly List
 
   _items = new List
  
   ();
  
 
 
        public IEnumerable
 
   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 constructor to inject repository to controller:

[Route(api/[controller])]
public class TodoController : Controller
{
    // Remove this code:
    //static readonly List
 
   _items = new List
  
   ()
  
 
    //{
    //    new TodoItem { Id = 1, Title = First Item }
    //};
 
    // Add this code:
    private readonly ITodoRepository _repository;
 
    public TodoController(ITodoRepository repository)
    {
        _repository = repository;
    }

 

Then update the controller Method to repository:

[HttpGet]
public IEnumerable
 
   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(GetByIdRoute, new { 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 the dependency Injection System to enable it. In the Startup class, add the following code:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    // New code
    services.AddSingleton
 
  ();
 
}

 

When an application is running, once the controller is created, the framework automatically injects TodoRepository into the controller, which will act on the entire application lifecycle.

Independent Application Deployment outside IIS

By default, When you click F5, the application runs in IIS Express. You can see the IIS Express icon in the toolbar.

 

ASP. NET 5.0 can be deployed on different servers. In this section, we will use WebListener that can run outside of IIS.

Note: deploying applications in IIS still has many advantages, such as security and progress management.

In the project. json file, add the 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 options to project. json.

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

 

"Commands" contains a list of predefined commands that can be passed to K runtime. In this example, "web" is the command name, which can be any actual command name value.

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

· -- The server flag is used to declare the server. In this example, It is WebListener.

· -- Server. urls indicates the URL to be listened.

Save the project. json file. In Solution Explorer, right-click the project and selectProperties. InPropertiesColumn, clickDebug. InDebug targetChange "IIS Express" to "web ".

 

Click F5 to run the App. Visual Studio then runs the console application that starts WebListener.

Open your browser and enter http: // localhost: 5000. You can see the welcome page.

To use IIS, change the Debug Target to "IIS Express" in the previous step.

 

 

Directory: ASP. NET 5 Series tutorials (1): reading new features ASP. NET 5 Series tutorial (II): Hello WorldASP. NET 5 Series tutorial (III): view components introduction ASP. NET 5 Series tutorials (4): Add services to the view and publish applications to the public cloud ASP. NET 5 Series tutorials (5): Use Grunt and Bower in Visual Studio 2015 to develop Web programs ASP. NET 5 Series tutorial (6): Create Web APIASP in MVC6. NET 5 Series tutorials (7)-interpreting code

Related Article

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.