Asp.NetCore 从控制台到WebApi

一、新建一个.NetCore控制台程序

二、添加依赖项

三、添加Startup.cs文件

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleWeb
{
    public class Startup
    {

        public void Configure(IApplicationBuilder app)
        {
            app.Run(context =>
            {
                return context.Response.WriteAsync("Hello world");
            });
        }
    }
}

四、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();
        }
    }
}

五、运行

浏览器输入localhost;5000

 六、加入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";
        }
    }
}

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");
            });
        }
    }
}

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

 七、添加页面,搭建webMVC application   没实现出来 老是找不到页面,解决了再更。。。。      

猜你喜欢

转载自www.cnblogs.com/awaTangjay/p/10303058.html