net core体系-web应用程序-1VS2017构建一个简单的web

使用vs2017,添加一个新项目-asp.net core web应用程序。

              

结构如图,

        wwwroot放了网站的静态资源如css、js、image文件;

        appsetting.json是应用程序的配置文件。

        buidlerconfig.json是应用程序的打包配置文件。

        page是应用程序的页面

        program.cs是程序的入口,代码如下,意思是创建一个站点,并从startup类开始运行。

 public class Program
{
    public static void Main(string[] args)
    {
           BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>WebHost.CreateDefaultBuilder(args).UseStartup<Startup>().Build();
}
         startup.cs是站点启动时具体做了哪些事情,主要是开启了一个mvc服务。

         打开page

         

 index 的结构和webform非常相似,在index.cshtml是视图页,.cs是后台程序, 里面有个onget方法标识被请求是触发。

上文提到这个应用程序是启动了一个mvc服务,那么我们能不能把这个webform型搞成mvc的呢,当然可以。

根目录下手动创建Controllers文件夹,并创建一个HomeController控制器,

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

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Core.Controllers
{
    public class HomeController : Controller
    {
          // GET: /<controller>/
         public IActionResult Index()
        {
               return View();
        }
    }
}

根目录下再创建Views文件夹,并添加一个Home文件夹并创建一个Index.cshtml视图,

@{
        Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
这是mvc的入口页
</body>
</html>
最后,startup.cs配置路由,找到

app.UseMvc();

追加代码
app.UseMvc(routes =>
{
      routes.MapRoute(
      name: "default",
      template: "{controller=Home}/{action=Index}/{id?}");
});

运行,在浏览器输入地址http://localhost:49265/Home/Index,运行成功。



IT黑马
原文地址:https://www.cnblogs.com/hmit/p/10757481.html