Fork me on GitHub

Owin 自定义中间件(2)中间件进阶

 前面一篇文章简单的介绍了中间件的应用

下面编写一个自定义的中间件类库,并加入中间件参数以及引入日志记录中间件的异常

下面来看下中间件的构造,参数可以自定义 这里我定义了一个参数类

编写中间件需要引入

Owin

Microsoft.Owin;

中间件类需要继承类:OwinMiddleware

 /// <summary>
    /// 自定义的中间件
    /// </summary>
    public class CustomMiddleware : OwinMiddleware
    {
        CustomMiddlewareParameters _parameter;
        public CustomMiddleware(OwinMiddleware next, CustomMiddlewareParameters parameter) : base(next)
        {
            _parameter = parameter;
        }
        public override Task Invoke(IOwinContext c)
        {
            if (Next != null)
            {
                try
                {
                    var cookie = c.Request.Cookies.ToList();
                    string allcookie = string.Empty;
                    string allenvi = string.Empty;
                    foreach (var cok in cookie)
                    {
                        allcookie += cok.Key + "---------------" + cok.Value + "<br />";
                        c.Environment.Add(cok.Key, cok.Value);
                    }

                    foreach (var envi in c.Environment)
                    {
                        allenvi += envi.Key + "---------------" + envi.Value + "<br />";
                    }

                    var msg = Encoding.UTF8.GetBytes(allcookie + "<br /><br /><br /><br /><br /><br />" + allenvi);
                    c.Response.ContentType = "text/html; charset=utf-8";
                    c.Response.Write(msg, 0, msg.Length);



                    //处理操作
                    return Next.Invoke(c);
                }
                catch (Exception ex)
                {
                    _parameter.logs.Error(ex.Message);
                }
            }
            return Task.FromResult<int>(0);
        }

    }
View Code

这里我获取了cookies  以及 设置或获取 IOwinContext上下文中的环境变量,那么这里就可以搞事情了

我可以处理cookies  添加设置环境变量中的值 或者根据Request  Response中的做处理,或者这个中间件做一些事情 另外其他中间件来搞事情,但是要注意中间件引用的顺序

下面看下我的参数类:CustomMiddlewareParameters

 public class CustomMiddlewareParameters
    {
        public ILog logs { get;  }
      
        public string siteName { get; set; }
        public LYMOptions lymOptions { get; set; }
        public CustomMiddlewareParameters()
        {
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "Log4Net.config"));
            this.logs = LogManager.GetLogger("CustomMiddlewareParameters");
            this.lymOptions = new LYMOptions();
        }

        internal void Validate()
        {
            if (siteName == null)
            {
                throw new ArgumentException("参数siteName不能设置为Null");
            }
            if (lymOptions == null)
            {
                throw new ArgumentException("参数cookieOptions不能设置为Null");
            }

        }

       

    }
View Code

参数里面可以引入更多的参数,看实际业务需求,这里我随便定义了一些,同时这里可以验证参数等操作,我写了几个异常未来抛出日志

这里日志我引入了Log4.Net 包 当然也用可以用其他的 包括自己写一些

做好这一步,那么我来写一个扩展类 扩展IAppbuilder 

 public static class CustomMiddlewareExtentions
    {
        public static IAppBuilder UseLYMMiddleware(this IAppBuilder builder, CustomMiddlewareParameters customParmeters)
        {
            try
            {
              customParmeters.Validate();
              builder.Use<CustomMiddleware>(customParmeters);
            }
            catch (Exception ex)
            {
                customParmeters.logs.Error(ex.Message);
            }
            return builder;
        }

      
    }
View Code

可以捕获一些异常情况,这句是中关键件的关键 builder.Use<CustomMiddleware>(customParmeters);

CustomMiddleware 为自定义的中间件类,参数为 params object []  

到这里中间件基本就写好了

下来就是用:

在Web应用中引用 Microsoft.Owin.Host.SystemWeb

在Web寄宿类中添加  中间件引用就ok了

   app.UseLYMMiddleware(new CustomMiddlewareParameters());

这里我没有添加参数 会报错,查看日志的生成情况,这里需要配置下日志的XML

检查下日志已搞定

接下来看下正常情况是什么,中间件里面我输处理日志信息 以及 中间件环境变量信息

下面看下上面的信息,在中间里面就可以搞事情了比如:参数相关,中间件上下文对象都封装有这个IOwinContext对象  

接下来看下这个中间件里面的参数

//
        // 摘要:
        //     Gets the Authentication middleware functionality available on the current request.
        //
        // 返回结果:
        //     The authentication middleware functionality available on the current request.
        IAuthenticationManager Authentication { get; }
        //
        // 摘要:
        //     Gets the OWIN environment.
        //
        // 返回结果:
        //     The OWIN environment.
        IDictionary<string, object> Environment { get; }
        //
        // 摘要:
        //     Gets a wrapper exposing request specific properties.
        //
        // 返回结果:
        //     A wrapper exposing request specific properties.
        IOwinRequest Request { get; }
        //
        // 摘要:
        //     Gets a wrapper exposing response specific properties.
        //
        // 返回结果:
        //     A wrapper exposing response specific properties.
        IOwinResponse Response { get; }
        //
        // 摘要:
        //     Gets or sets the host.TraceOutput environment value.
        //
        // 返回结果:
        //     The host.TraceOutput TextWriter.
        TextWriter TraceOutput { get; set; }

        //
        // 摘要:
        //     Gets a value from the OWIN environment, or returns default(T) if not present.
        //
        // 参数:
        //   key:
        //     The key of the value to get.
        //
        // 类型参数:
        //   T:
        //     The type of the value.
        //
        // 返回结果:
        //     The value with the specified key or the default(T) if not present.
        T Get<T>(string key);
        //
        // 摘要:
        //     Sets the given key and value in the OWIN environment.
        //
        // 参数:
        //   key:
        //     The key of the value to set.
        //
        //   value:
        //     The value to set.
        //
        // 类型参数:
        //   T:
        //     The type of the value.
        //
        // 返回结果:
        //     This instance.
        IOwinContext Set<T>(string key, T value);
View Code

Authentication:授权相关

Environment:上下文环境值  IDictionary<string, object> 这个类型

OwinRequest Request :封装的请求对象

IOwinResponse Response 请求的响应对象

以及一个 Get  Set 方法 这是设置 OWIN environment中的值

还有对输出处理  TraceOutput

中间件想一个生产企业的流水线一样,一次请求过来 经过流水线(不同的中间件)加工处理,最后到生产出产品就相当于网页的Reponse响应

 

posted @ 2017-11-22 16:52  龙码精神  阅读(1027)  评论(0编辑  收藏  举报