微服务Demo

第1章 1.1 开发一个API 服务 (webapi)

2018-10-09  本文已影响435人  elef

ubuntu下安装 dotnet
https://www.microsoft.com/net/download/linux-package-manager/ubuntu18-04/sdk-current
.net core 文档
https://docs.microsoft.com/zh-cn/dotnet/core/tools/dotnet-new?tabs=netcore21

首先使用dotnet 提供的脚手架创建应用

在主目录下 demo 文件下,右键【在终端打开】

输入命令,创建一个名为 chapter1-webapi 的webapi类型的例子

dotnet new webapi -n chapter1-webapi

运行程序

dotnet restore
dotnet run

控制台输出:

daijinming@dai-u:~/demo/chapter1-webapi$ dotnet run
Using launch settings from /home/daijinming/demo/chapter1-webapi/Properties/launchSettings.json...
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
      User profile is available. Using '/home/daijinming/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Hosting environment: Development
Content root path: /home/daijinming/demo/chapter1-webapi
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

在 /Controllers/ValuesController.cs 中是默认预置的API代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace chapter1_webapi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {

        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {   
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

在使用postman测试API的时候注意关闭“SSL certificate verification” ,设置方式:File->Setting->General->SSL certificate verification。因为之前运行 dotnet run 的时候开始了 https://localhost:5001 服务,如果不忽律证书的话postman测试的时候根本获得不来任何输出。
POSTMAN中的代码

GET /api/Values HTTP/1.1
Host: localhost:5000
Cache-Control: no-cache
Postman-Token: fe637e3e-5038-43f7-ab26-8e5963e961c3

输出信息

[
    "value1",
    "value2"
]
上一篇下一篇

猜你喜欢

热点阅读