Asp.net Core MVC 个人总结

框架架构:

1.Properties:配置文件

1.1.launchSettings.json:启动配置文件,为asp.net core 应用保存持有的配置,用于启动准备的工作,包括环境变量,开发端口。

{

  //IIS调试配置

  "iisSettings": {

    "windowsAuthentication": false,//是否启动windows身份验证

    "anonymousAuthentication": true,//是否启用匿名身份验证

    "iisExpress": {

      "applicationUrl": "http://localhost:26222/",//IIS Express启动端口地址

      "sslPort": 0

    }

  },

  "profiles": {

    "IIS Express": {

      "commandName": "IISExpress",

      "launchBrowser": true,

      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"

      }

    },

    //Core调试配置

    "WebApplication1": {

      "commandName": "Project",

      "launchBrowser": true,

      "environmentVariables": {

        "ASPNETCORE_ENVIRONMENT": "Development"

      },

      "applicationUrl": "http://localhost:26223" //#本地自宿主端口

    }

  }

}

 

2.wwwroot:站点静态文件

2.1.css:样式文件

2.2.images:图片文件

2.3.js:javascript文件

2.4.lib:系统内置的js和style文件

2.5.index.html:http://localhost:5001/index.html访问

 

3.appsettings.json

配置如下:

{

  "Logging": {

    "IncludeScopes": false,

    "LogLevel": {

      "Default": "Warning"

    }

  },

  "appset": {

    "api": "http://localhost:50961/api/"

  },

  "apptype": {

    "new": "10016"

  }

}

获取参数值:

public class Startup

{

public IConfigurationRoot Configuration { get; }

// 这个方法在运行时调用。使用此方法来配置HTTP请求管道。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

{

/** begin 公共参数appset/ api **/

    Config.apiurl = Configuration.GetSection("appset").GetValue<string>("api").ToString();

}

}

 

  1. bundleconfig.json:MVC样式文件、脚本文件引用

[

  {

    "outputFileName": "wwwroot/css/site.min.css",

    // An array of relative input file paths. Globbing patterns supported

    "inputFiles": [

      "wwwroot/css/site.css",

      "wwwroot/css/style.css"

    ]

  },

  {

    "outputFileName": "wwwroot/js/site.min.js",

    "inputFiles": [

      "wwwroot/js/site.js"

    ],

    // Optionally specify minification options

    "minify": {

      "enabled": true,

      "renameLocals": true

    },

    // Optionally generate .map file

    "sourceMap": false

  }

]

 

5.Program.cs:项目启动入口

public static void Main(string[] args)

{

  public static void Main(string[] args)

  {

var host = new WebHostBuilder()

                .UseKestrel()

                .UseContentRoot(Directory.GetCurrentDirectory())

                .UseIISIntegration()

                .UseStartup<Startup>()

                .UseUrls("http://*:5001,http://*:5002")

                .UseApplicationInsights()

                .Build();         

host.Run();

  }

}

.UseUrls("http://*:5001,http://*:5002"):代表使用http://localhost:5001和http://localhost:5002都可以访问。

 

6.Startup.cs:Asp.Net Core启动入口文件

 

 

MVC编程

1.ActionResult类是所有操作结果的基类。 以下是不同类型的操作结果及其行为的列表

名称

作用

ContentResult

返回字符串

FileContentResult

返回文件内容

FilePathResult

返回文件内容

FileStreamResult

返回文件内容。

EmptyResult

不返回任何内容

JavaScriptResult

返回要执行的脚本

JsonResult

返回JSON格式的数据

RedirectToResult

重定向到指定的URL

HttpUnauthorizedResult

返回403 HTTP状态代码

RedirectToRouteResult

重定向到不同的操作/不同的控制器操作

ViewResult

作为视图引擎的响应接收

PartialViewResult

接收作为视图引擎的响应

 

public ContentResult Index() 

  return Content("Hello, World! this message is from Home Controller using the Action Result")

 

  1. Area区域:

2.1.Startup配置:

public class Startup

{

// 这个方法在运行时调用。使用此方法来配置HTTP请求管道。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)

 {

   app.UseMvc(routes =>

            {

                 routes.MapRoute(

                    name: "default",

                    template: "{controller=Home}/{action=Index}/{id?}");

                 routes.MapRoute(

                    name: "Admin",

                    template: "{area=Admin}/{controller=Home}/{action=Index}/{id?}");

                 routes.MapRoute(

                   name: "Member",

                   template: "{area=Member}/{controller=Home}/{action=Index}/{id?}");

            });

}

}

 

2.2.添加文件夹目录:

 

2.3.控制器配置

namespace ApiWeb.Areas.Admin.Controllers

{

    [Area("Admin")]//区域名称

    public class HomeController : Controller

    {

        public IActionResult Index()

        {

            return View();

        }

    }

}

 

2.4.访问

http://localhost:5001/Admin/Home/Index

 

  1. Filiter 过滤器:

参考地址:http://www.cnblogs.com/tdfblog/p/filters-in-aspnet-core-mvc.html

同步过滤器定义OnStageExecuting和OnStageExecuted方法,会在管道特定阶段之前和之后运行代码的。

异步过滤器定义了一个OnStageExecutionAsync方法。该方法提供了FilterTypeExecutionDelegate的委托,当调用该委托时会执行具体管道阶段的工作。

ASP.NET Core 有以下五种类型的过滤器,每个过滤器类型在过滤器管道中的不同阶段执行:

1.Authorization Filter

授权过滤器 在过滤器管道中第一个执行,通常用于验证当前请求的合法性,不合法后面的管道会直接跳过。它们只有一个Before方法,不像其它大多数过滤器支持前置阶段方法和后置阶段方法。注意,您不要在授权过滤器中抛出异常,因为没有任何代码来处理异常(异常过滤器不处理它们)

2.Resource Filter

资源过滤器是第二个运行,在 Authorization Filter 之后,Model Binding 之前执行。在性能方面,资源过滤器在实现缓存或截断过滤器管道尤为重要

3.Action Filter

使用率最高的过滤器,在调用 Acioin 方法之前和之后执行代码。跟 Resource Filter 很类似,但 Model Binding 在之后执行

4.Exception Filter

用于为应用程序执行异常处理策略。

5.Result Filter

Action 执行完成后,最后会执行过滤器。用于处理ActionResult结果输出策略。

 

ASP.NET Core 的每个请求都会先经过已注册的Middleware,接着才会执行过滤器:同类型的过滤器都会以先进后出的方式执行。

 

 

配置过滤器过程:

public class Startup

{

public void ConfigureServices(IServiceCollection services)

     {

            // 添加过滤器或服务

            services.AddMvc(options=> {

// 添加错误处理过滤器

                options.Filters.Add(new CustomErrorAttribute());

            });

     }

}

/// <summary>

/// 全局页面控制器异常记录

/// </summary>

public class CustomErrorAttribute:ExceptionFilterAttribute

{

    public override void OnException(ExceptionContext filterContext)

    {

            base.OnException(filterContext);

            Dictionary<string, object> dic = new Dictionary<string, object>();

            dic.Add("code", -1);

            dic.Add("msg", filterContext.Exception.ToString().Replace("\"", ""));

            string jsons = JsonString.JsonData(dic);

            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");

            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Credentials", "true");

            HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

            HttpContext.Current.Response.ContentType = "application/Json";

            HttpContext.Current.Response.Write(jsons);

            HttpContext.Current.Response.End();

            //设置为true阻止golbal里面的错误执行

            filterContext.ExceptionHandled = true;

    }

}

 

转载于:https://www.cnblogs.com/liyinsheng/p/7687465.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值