6月 17

我做东西喜欢从最简单开始。这样方便梳理每个细节。今天弄个.net core的站点试试。

开发工具vs2017,新建项目 .net core 下的 asp.net core web application 

.net framework 选择最高的4.6.1 创建一个空的站点

 

空网站已经引用了两个包

Microsoft.ApplicationInsights.AspNetCore
Microsoft.AspNetCore

删除Startup自带的代码文件只保留两个方法体 ConfigureServices和Configure

 

增加mvc框架支持

添加nuget包引用

Microsoft.AspNetCore.Mvc

添加startup->ConfigureServices

services.AddMvc();

添加startup->Configure

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}");
});

 按照mvc规则给项目添加Controllers和Home文件夹,并且添加简单的action和view。运行即可看到结果。

 

使用Session

比较多,特地重写了一篇

asp.net core中使用session

written by ocean \\ tags: ,

9月 19

做了一个公司项目,里面有用到一些验证吗,使用的是Attribute的方式

在此记录一下遇到的方式

 

最常见的不允许空

        [Required(ErrorMessage = "The UserName field is required.")]
        public string UserName { get; set; }

 

使用正则验证邮件地址

        [RegularExpression(@"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]+$", ErrorMessage = "Incorrect email address.")]
        public string Email { get; set; }

 

验证长度

        [StringLength(16, MinimumLength = 8)]
        [Required(ErrorMessage = "The Password field is required.")]
        [Remote("CheckPassword", "Auth", ErrorMessage = "The password must have minimum 8 characters which consist 3 of number,capital, small letter and symbol.")]
        public string Password { get; set; }

这里还使用了Remote验证,用来做一些需要后台处理的特别的验证,这里用来检验密码强度。

其中Auth位Controller,CheckPassword是Action名字

后台代码如下

        public ActionResult CheckPassword(string password)
        {
            //字符统计
            int number = 0, lower = 0, upper = 0, symbol = 0;
            if (password != null && password.Length > 0)
            {
                foreach (char c in password)
                {
                    if (c >= '0' && c <= '9') number = 1;
                    else if (c >= 'a' && c <= 'z') lower = 1;
                    else if (c >= 'A' && c <= 'Z') upper = 1;
                    else symbol = 1;
                }
            }
            var result = false;
            if (number + lower + upper + symbol >= 3) //包含三种
            {
                result = true;
            } 
            return Json(result, JsonRequestBehavior.AllowGet);
        }

 

另外密码确认还用到了Compare

        [DataType(DataType.Password)]
        [System.ComponentModel.DataAnnotations.Compare("Password")]
        [Required(ErrorMessage = "The Confirm Password field is required.")]
        [Display(Name = "Confirm Password")]
        public string ConfirmPassword { get; set; }

这里面的参数就是要校验一致的字段名

Display则是用来做前台显示用。

written by ocean \\ tags:

10月 11

以前在做webform的时候,url控制都是自己在httphandler里面写的

打算新开一个站,用mvc的方式,因为规划有多个二级域名,而不是子目录,所以研究了一下mvc的路由配置方式,特此记录

配置形式如下

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


            routes.Add("weixin", new DomainRoute("weixin.zuotu5.com", "{action}", new { controller = "WeiXin", action = "Index" }));
            routes.Add("zhifubao", new DomainRoute("zhifubao.zuotu5.com", "{action}", new { controller = "ZhiFuBao", action = "Index" }));
            routes.Add("qq", new DomainRoute("qq.zuotu5.com", "{action}", new { controller = "QQ", action = "Index" }));
            routes.Add("tucao", new DomainRoute("tucao.zuotu5.com", "{action}", new { controller = "PeiZi", action = "Index" }));
            routes.Add("www", new DomainRoute("zuotu5.com", "{action}", new { controller = "WWW", action = "Index" }));

        }
    }

如此,便配置了5个二级域名

其中用到了类DomainRoute,

    public class DomainRoute : Route
    {
        private Regex domainRegex;
        private Regex pathRegex;

        public string Domain { get; set; }

        public DomainRoute(string domain, string url, RouteValueDictionary defaults)
            : base(url, defaults, new MvcRouteHandler())
        {
            Domain = domain;
        }

        public DomainRoute(string domain, string url, RouteValueDictionary defaults, IRouteHandler routeHandler)
            : base(url, defaults, routeHandler)
        {
            Domain = domain;
        }

        public DomainRoute(string domain, string url, object defaults)
            : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
        {
            Domain = domain;
        }

        public DomainRoute(string domain, string url, object defaults, IRouteHandler routeHandler)
            : base(url, new RouteValueDictionary(defaults), routeHandler)
        {
            Domain = domain;
        }

        public override RouteData GetRouteData(HttpContextBase httpContext)
        {
            // 构造 regex
            domainRegex = CreateRegex(Domain);
            pathRegex = CreateRegex(Url);

            // 请求信息
            string requestDomain = httpContext.Request.Headers["host"];
            if (!string.IsNullOrEmpty(requestDomain))
            {
                if (requestDomain.IndexOf(":") > 0)
                {
                    requestDomain = requestDomain.Substring(0, requestDomain.IndexOf(":"));
                }
            }
            else
            {
                requestDomain = httpContext.Request.Url.Host;
            }
            string requestPath = httpContext.Request.AppRelativeCurrentExecutionFilePath.Substring(2) + httpContext.Request.PathInfo;

            // 匹配域名和路由
            Match domainMatch = domainRegex.Match(requestDomain);
            Match pathMatch = pathRegex.Match(requestPath);

            // 路由数据
            RouteData data = null;
            if (domainMatch.Success && pathMatch.Success)
            {
                data = new RouteData(this, RouteHandler);

                // 添加默认选项
                if (Defaults != null)
                {
                    foreach (KeyValuePair<string, object> item in Defaults)
                    {
                        data.Values[item.Key] = item.Value;
                        if (item.Key.Equals("area") || item.Key.Equals("Namespaces"))
                        {
                            data.DataTokens[item.Key] = item.Value;
                        }
                    }
                }

                // 匹配域名
                for (int i = 1; i < domainMatch.Groups.Count; i++)
                {
                    Group group = domainMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = domainRegex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                                if (key.Equals("area"))
                                {
                                    data.DataTokens[key] = group.Value;
                                }
                            }
                        }
                    }
                }

                // 匹配路径
                for (int i = 1; i < pathMatch.Groups.Count; i++)
                {
                    Group group = pathMatch.Groups[i];
                    if (group.Success)
                    {
                        string key = pathRegex.GroupNameFromNumber(i);

                        if (!string.IsNullOrEmpty(key) && !char.IsNumber(key, 0))
                        {
                            if (!string.IsNullOrEmpty(group.Value))
                            {
                                data.Values[key] = group.Value;
                                if (key.Equals("area"))
                                {
                                    data.DataTokens[key] = group.Value;
                                }
                            }
                        }
                    }
                }
            }

            return data;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
            return base.GetVirtualPath(requestContext, RemoveDomainTokens(values));
        }

        public DomainData GetDomainData(RequestContext requestContext, RouteValueDictionary values)
        {
            // 获得主机名
            string hostname = Domain;
            foreach (KeyValuePair<string, object> pair in values)
            {
                if (pair.Key == "area" && string.IsNullOrEmpty(pair.Value.ToString()))
                {
                    hostname = hostname.Replace("{" + pair.Key + "}", "www");
                }
                else
                {
                    hostname = hostname.Replace("{" + pair.Key + "}", pair.Value.ToString());
                }
            }

            //如果域名的area还没有被替换,说明路由数据里没有area,恢复为顶级域名
            if (hostname.Contains("{area}"))
            {
                hostname = hostname.Replace("{area}", "www");
            }

            RemoveDomainTokens(values);

            // Return 域名数据
            return new DomainData
            {
                Protocol = "http",
                HostName = hostname,
                Fragment = ""
            };
        }

        private Regex CreateRegex(string source)
        {
            // 替换
            source = source.Replace("/", @"\/?");
            source = source.Replace(".", @"\.?");
            source = source.Replace("-", @"\-?");
            source = source.Replace("{", @"(?<");
            source = source.Replace("}", @">([a-zA-Z0-9_]*))");

            return new Regex("^" + source + "$");
        }

        private RouteValueDictionary RemoveDomainTokens(RouteValueDictionary values)
        {
            Regex tokenRegex = new Regex(@"({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?({[a-zA-Z0-9_]*})*-?\.?\/?");
            Match tokenMatch = tokenRegex.Match(Domain);
            for (int i = 0; i < tokenMatch.Groups.Count; i++)
            {
                Group group = tokenMatch.Groups[i];
                if (group.Success)
                {
                    string key = group.Value.Replace("{", "").Replace("}", "");
                    if (values.ContainsKey(key))
                        values.Remove(key);
                }
            }

            return values;
        }
    }

    public class DomainData
    {
        public string Protocol { get; set; }
        public string HostName { get; set; }
        public string Fragment { get; set; }
    }

written by ocean \\ tags: