ASP. NET MVC + Redis (hash inbound +log4net integration)

Source: Internet
Author: User

Blog Four Elements

Since you want to write a blog-like website, you should know the information about the blog.

title author Time content
Title Author Time Content

Because prior to know Redis, so a little tangled in the data storage, the final decision or according to the book written step by step, and then decide whether it is necessary to make changes.

The storage methods described in the book are as follows:

Post:count Title Little Ape's Blog
Author Little Ape
Time 2018.5.17
Content The world is so wonderful, I choose the programmer

Look, all the content of the blog is stored in hashset form (current state), ensuring that the uniqueness of the stored content depends on the count of Post:count , which should resemble the self-increment variable.

  1. Since it is object-oriented programming, the first thing must be to create an entity class;

    using System;using System.Collections.Generic;using System.Text;using Blog.Common;namespace Blog.Models{public class BLogModel{    public BLogModel(string title, string author, DateTime time, string content)    {        bool flag = true;        if (!title.IsNullOrEmpty())            this.title = title;        else            flag = false;        if (!author.IsNullOrEmpty())            this.author = author;        else            flag = false;        if (time == null)            flag = false;        else            this.time = time;        if (!content.IsNullOrEmpty())            this.content = content;        else            flag = false;            if(flag==false)            {                throw new ApplicationException("创建BLogModel实体有必填字段为空");            }    }    public string title { get; set; }    public string author { get; set; }    public DateTime time { get; set; }    public string content { get; set; }}}

    To create this entity class, I have two main things to do outside of the definition field.

    ① because no method was found in my SDK, write an extension method for string isnullorempty;

    ② each Blog object should be complete, that is, each field is required, because Redis storage is used only in C # to determine the required fields;

    Here's another question, usually to establish an association between an article's thumbnail name and an article ID. The purpose of this is to ensure the uniqueness of the article and to comply with some of the website URL specifications of the operation. However, it is not intended to enable this operation at this time.

  2. Tangled Way of warehousing

    Originally I think is to get the data in the controller and then call Rediscommon method to get a connection object to add a bit, but the code to write a long line to fix exist judgment, a little endure. or decided to throw all the data to the Rediscommon class and ask him to do it.

    The first time I opened this class I decided to write an extension method (I might have been obsessed with writing extensions lately), just the opposite of the previous todic, which was to put dictionary

     public static HashEntry[] ToHashEntry(this Dictionary<string, string> dic)    {        List<HashEntry> list = new List<HashEntry>();        foreach (var item in dic.Keys)        {            list.Add(new HashEntry(item, dic[item]));        }        return list.ToArray();    }

    The purpose of writing this method is to feel that there will be a lot of dictionaries into the hashentry array of cases, it may be more convenient to use, and then you can happily write the method of storage.

     public static void SetBLog(BLogModel bLog)    {        string postCount = GetData().StringIncrement("post:count").ToString();        Dictionary<string, string> dic = new Dictionary<string, string>();        dic.Add("title", bLog.title);        dic.Add("author", bLog.author);        dic.Add("time", bLog.time.ToString());        dic.Add("content", bLog.content);        try        {            GetData().HashSet("post:"+postCount, dic.ToHashEntry());        }        catch (Exception e)        {            throw e;        }    }

    Although you do not want to use the abbreviation name and ID Association relationship of this function, but still write it, save the trouble later.

     public static bool SetSlugToId(string slug, string id)    {        if (!GetData().HashExists("slug.to.id", slug))        {            GetData().HashSet("slug.to.id", slug, id);            return true;        }        return false;    }
  3. Integrated log4net

    Log4net is very familiar with, although the various logs can be hit into the database, but the most useful is the log file.

    So the starting or dotnet CLI command dotnet Add package log4net

    Here to mention, ready to have time to understand the bower, if it can be done, just play.

    Then the following steps are described

      • Create a file named Log4net.config.
      • Loads the log4net in the project initiation method.
      • Create a global exception class, actually can not use this class, but feel good to add in.

    Log4net.config

      <?xml version= "1.0" encoding= "Utf-8"?><configuration><!--This section contains the Log4net Configuration settings--><log4net><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= "ten"/> <maximumfilesize value= "1MB"/> <layout type= "log4net. Layout.patternlayout "> <conversionpattern value="%date [%thread]%-5level%logger-%message%newline "/> < /layout></appender><!--Setup The root category, add the Appenders and set the default level--><root>  ; <level value= "All"/> <appender-ref ref= "Rollinglogfileappender"/></root></log4net></ Configuration>  

    Loading Log4net in the startup file actually adds three lines of code to the original.

    What needs to be said here is that when creating a static iloggerrepository, the most resourceful way is to create a solution dotnet new SLn , fill in the project, and solve the problem with vs.

      public static ILoggerRepository repository{get;set;}    public Startup(IConfiguration configuration)    {        Configuration = configuration;        //加载log4net日志配置文件        repository = LogManager.CreateRepository("NETCoreRepository");        XmlConfigurator.Configure(repository, new FileInfo("log4net.config"));    }

    Global Exception class

    using log4net;using Microsoft.AspNetCore.Mvc.Filters;using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;namespace Blog{public class HttpGlobalExceptionFilter : IExceptionFilter{    private ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HttpGlobalExceptionFilter));    public void OnException(ExceptionContext context)    {        log.Error(context.Exception);    }}}

    Log is used, in general it is sufficient to put the log object in the base class.

     protected static ILog log = LogManager.GetLogger(Startup.repository.Name, typeof(HttpGlobalExceptionFilter)); log.Info("log test fisish");

ASP. NET MVC + Redis (hash inbound +log4net integration)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.