C# netcore 控制台形式添加webapi

原文链接 https://www.cnblogs.com/awaTangjay/p/10303058.html

新建一个.NetCore控制台程序

添加依赖项

Program.cs文件添加 Microsoft.AspNetCore.Hosting 引用,创建WebHost对象

复制代码
using Microsoft.AspNetCore.Hosting;
using System;
using System.IO;

namespace myFirstConsoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseStartup<Startup>()
            .Build();

            host.Run();
        }
    }
}
复制代码

 添加Startup.cs文件 

Startup.cs中加入ConfigureServices方法

复制代码
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleWeb
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc(s=> {
                s.MapRoute("default", "{controller}/{action}/{id?}", "test/index");
            });
            app.Run(context =>
            {
                return context.Response.WriteAsync("Hello world");
            });
        }
    }
}
复制代码

加入WebApi

项目根目录下添加一个Api文件夹用来放Api,在Api中新建一个TestApi.cs 继承自ControllerBase

复制代码
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleWeb.Api
{
    public class TestApi:ControllerBase
    {
        [Route("test/index")]
        public string Index()
        {
            return "hello api";
        }
    }
}
复制代码

运行程序、在浏览器地址栏中输入localhost:5000/test/index

作者:xyyhqq

-------------------------------------------

Never Stop !

原文地址:https://www.cnblogs.com/xyyhcn/p/15032246.html