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 that controller. In this example, the routing naming convention is the prefix for the corresponding controller, and for the Todocontroller class, the routing template is "Api/todo".

HTTP method

The [HttpGet],[HttpPost] , and [Httpdelete] Properties define the HTTP method corresponding to the controller action (there are also [Httpput] and [Httppatch] property, not used in this example. )

[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 increase the delivery information for the route. Therefore, the route template is more perfect to be written as "Api/[controller]/{id:int}".

In "{Id:int}", the ID is a variable, and ": int" means the parameter is an integral type. The following URLs are examples:

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

cannot be written as:

Http://localhost/api/todo/abc

Note the GetById and DeleteItem methods also have parameters named ID. The framework automatically passes the actual parameter values into the controller. For example, if the value of the URL is Http://localhost/api/todo/42,id is 42, the procedure is a parameter binding.

The Createtodoitem method represents another parameter binding:

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

The [Frombody] property specifies that the framework deserializes the Todoitem parameter from 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 because of other uses. For example ' Get/api/todo/abc ', the ' abc ' argument 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 is JSON, and clients can also 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, and the page throws 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 this approach is that it is difficult to unit test. (For a test-related discussion, refer to the unit testing Controllers in ASP. NET Web API).

Dependency Injection

MVC 6 has built-in dependency injection capabilities. Below, let's create a repository class that contains a todo list.

First, 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 specific 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 the dependency injection system 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> ();
}

Once the controller is created, the framework automatically injects todorepository into the controller as the application runs, and it acts on the entire application lifecycle.

Standalone deployment of apps outside of IIS

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

ASP. NET 5.0 can be deployed to different servers, and in this section we will use Weblistener that can run 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 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": {
        "": "Microsoft.AspNet.Hosting--server Microsoft.AspNet.Server.WebListener--server.urls/http// localhost:5000"
    }
}

The "commands" contains a list of predefined directives that can be passed to the K runtime. In this example, "Web" is the instruction name, which can be any 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, in this case Weblistener.

· The--server.urls tag provides a URL to listen to.

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 run the app. Visual Studio will then run a console app that starts Weblistener.

Open the browser and enter http://localhost:5000. You can see the Welcome screen.

If you need to use IIS, 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.

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

Directory:
    • 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 and publishing to a view apply to 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.