zoukankan      html  css  js  c++  java
  • 无废话,用.net core mvc 开发一个虽小但五脏俱全的网站

    .net core mvc 发布有很长时间了,但是一直没有用过,最近突然想开发一个导航网站,于是就抽时间开发了一个专门为开发者使用的导航站点,想看的话请移步我的上一篇博客https://www.cnblogs.com/weiwin/p/11941684.html
    这个网站虽然小但是网站该有的功能它都有。如果你想做一个小的网站,看这个帖子足够了,下面全是代码干货,没有废话

    1 登录过滤器设置
    新建一个类,继承 ActionFilterAttribute重写OnActionExecuting方法

     public class LoginFilter :ActionFilterAttribute
        {
           
          
            public FilterLogin()
            {
               
            }
            public override void OnActionExecuting(ActionExecutingContext context)
            {
                base.OnActionExecuting(context);
    
            //登录逻辑
            //----
            //如果没有登录
             context.Result = new StatusCodeResult(401);
               
            }
        }
        //控制器里使用
         [HttpPost]
         [FilterLogin()]
            public IActionResult GetUser()
            {
            }
    

    坑:这里一定注意要设置context.Result不然还会继续执行控制器里的方法

    2 全局异常日志设置
    nuget引用log4net
    配置log4net.config文件

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <!-- This section contains the log4net configuration settings -->
      <log4net>
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
          <layout type="log4net.Layout.PatternLayout" value="%date [%thread] %-5level %logger - %message%newline" />
        </appender>
        <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
          <file value="logfile/" />
          <appendToFile value="true" />
          <rollingStyle value="Composite" />
          <staticLogFileName value="false" />
          <datePattern value="yyyyMMdd'.log'" />
          <maxSizeRollBackups value="10" />
          <maximumFileSize value="1MB" />
          <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
          </layout>
        </appender>
    
        <!-- Setup the root category, add the appenders and set the default level -->
        <root>
          <level value="ALL" />
          <appender-ref ref="ConsoleAppender" />
          <appender-ref ref="FileAppender" />
          <appender-ref ref="RollingLogFileAppender" />
        </root>
      </log4net>
    </configuration>
    
    

    在startup里添加代码

    public static ILoggerRepository repository { get; set; }
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
                repository=LogManager.CreateRepository("NETCoreRepository");
                XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));
            }
              public void ConfigureServices(IServiceCollection services)
            {
                  services.AddMvc(options => { options.Filters.Add<FunClass.ErrorFilter>(); })
            }
    

    新建类ErrorFilter

     public class ErrorFilter : IExceptionFilter
        {
            private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HttpGlobalExceptionFilter));
            public void OnException(ExceptionContext context)
            {
                log.Error(context.Exception);
            }
    
        }
    

    3 缓存IMemoryCache使用
    在startup里添加代码

     services.AddMemoryCache();
    

    在控制器里使用

     private IMemoryCache _cache;
            public HomeController(IMemoryCache cache)
            {
               
                _cache = cache;
              
                
            }
    

    4 session使用
    在statup.cs里添加代码

    public void ConfigureServices(IServiceCollection services)
            {
                services.AddSession();
            }
     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                app.UseSession();
            }
    

    坑:这里必须在services.AddMvc()之后。

    5 手动获取DI对象
    有时候我们需要手动获取注入的对象,比如在过滤器里要使用缓存可以这样写

    IMemoryCache _cache = (IMemoryCache)context.HttpContext.RequestServices.GetService(typeof(IMemoryCache));
    

    还有第二种方法
    新建类ServiceLoader

      public class ServiceLoader
        {
            public static IServiceProvider Instance { get; set; }
        }
    

    在startup.cs 添加代码

     public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
            ServiceLoader.Instance = app.ApplicationServices;
            }
    

    使用

    (IMemoryCache)FunClass.ServiceLocator.Instance.GetService(typeof(IMemoryCache));
    

    完结散花。
    如果大家喜欢的话,别忘点了个站,下篇博客,我将把一个网站怎么从购买域名,备案,域名解析,发布部署.net core mvc站点的过程及遇到的坑讲一遍。

  • 相关阅读:
    java将pdf转成base64字符串及将base64字符串反转pdf
    input校验不能以0开头的数字
    js校验密码,不能为空的8-20位非纯数字或字母的密码
    tomcat正常关闭,端口号占用解决 StandardServer.await: create[8005]:
    Eclipse中项目报Target runtime com.genuitec.runtime.generic.jee60 is not defined异常的解决
    Access restriction: The type Base64 is not accessible due to restriction on
    [操作系统] 线程和进程的简单解释
    ssh登录一段时间后断开的解决方案
    [SAMtools] 常用指令总结
    [C] 有关内存问题
  • 原文地址:https://www.cnblogs.com/weiwin/p/11943075.html
Copyright © 2011-2022 走看看