• 开发环境
  • 打开vs,建立项目
  • 项目模板
  • 修改startup类代码
    • configureservices方法
    • configure方法
  • 新建一个controller
  • f5运行

图文说明,注意流量.

开发环境

  • visual studio 2019
  • .net core 2.x

打开vs,建立项目

建好之后就像下面这样

继续再建立两个.net core类库项目分别是 apistudy.coreapistudy.infrastructure

  • 右击解决方案,新建项目.
  • 选择 .netcore类库项目.
  • 输入项目名.
  • apistudy.core项目建立完成
  • 同样的方法再建立apistudy.infrastructrue 项目.
  • 完成之后如图
  • 然后设置依赖关系

项目模板

一个解决方案下三个项目:

  • xxxx.core
    放一些核心的东西,比如 entity(实体) 类
  • xxxx.infrastructure
    放一些数据库连接之类(dbcontext)的
  • xxxx.api
    网站项目

修改startup类代码

namespace apistudy.api
{
    using microsoft.aspnetcore.builder;
    using microsoft.aspnetcore.hosting;
    using microsoft.extensions.dependencyinjection;

    public class startup
    {
        // this method gets called by the runtime. use this method to add services to the container.
        // for more information on how to configure your application, visit https://go.microsoft.com/fwlink/?linkid=398940
        public void configureservices(iservicecollection services)
        {
            services.addmvc();
        }

        // this method gets called by the runtime. use this method to configure the http request pipeline.
        public void configure(iapplicationbuilder app, ihostingenvironment env)
        {
            if (env.isdevelopment())
            {
                app.usedeveloperexceptionpage();
            }

            app.usemvc(); //使用默认路由
        }
    }
}

configureservices方法

用来向容器中注册服务,注册好的服务可以在其他地方进行调用.

configure方法

用来配置中间件管道,即如何响应http请求.

新建一个controller

代码如下:

namespace apistudy.api.controllers
{
    using microsoft.aspnetcore.mvc;

    [route("api/[controller]")]
    [apicontroller]
    public class usercontroller:controller
    {
        public iactionresult get()
        {
            return ok("hello");
        }
    }
}

修改lauchsetting.json如下:

{
  "profiles": {
    "apistudy.api": {
      "commandname": "project",
      "launchbrowser": true,
      "applicationurl": "https://localhost:5001;http://localhost:5000",
      "environmentvariables": {
        "aspnetcore_environment": "development"
      }
    }
  }
}

f5运行

浏览器访问 https://localhost:5001/api/user