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 

編輯    .csproj文件

到HomeController.cs文件中 選中要添加視圖的Action

添加成功后會自動引入以下幾個NuGet包

現在運行 就可以看到頁面了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM