热线(9:00-18:00):13544706711
当前位置: 首页 > 教程技巧 > 

一些踩过的坑

时间: 2016/10/30 13:04:07

1)关于特性过滤器
    这个我们经常用到,一般用在捕捉异常还有权限控制等方面,这个用着比较方便,但是这个确隐藏着一个坑,就是呢,特性过滤器会在被第一次访问的时候创建一次,仅仅会被创建一次,然后就被aspnet缓存下来,之后就是取缓存了。
所以说如果我们要定义特性类的话,必须要注意一点就是里面不能包含状态可变的局部变量,因为会存在线程安全问题
2)关于nuget程序集版本
我们程序里面用到nuget的地方有很多,但是有的时候我们会出现不同程序集引用的nuget包版本不一样,但是程序编译完成之后web目录下只会有一个版本的dll,这样如果是强名称的包的话就会抛出版本异常,所以这种情况我建议是尽量保持所有程序集版本相同。
当然还有一个应急解决方案,就是webconfig下会有这么个节点
这个节点的作用就是程序集重定向,做程序集版本检查的时候对old版本的引用会被重定向到新版本
3)关于集合的线程安全
Dictionary<,>,List<>:
线程非安全:
添加删除操作都会维护一个version字段,每次+1
然后生成的迭代器的时候会传入version版本号,然后呢,迭代的时候会判断迭代器的version是否和version相同,如果不同则抛出异常
所以说如果发生并发操作,一个线程正在查询dic的时候另一个线程对这个dic做了修改则会抛出异常
ConcurrentDictionary
线程安全
采用了 volatile 来设置和取值
没有维护version字段
4)关于Https
目前由于我们需要使用https,所以页面也会针对请求内容来进行兼容,http的请求需要返回http后缀的静态内容,https的要返回带https后缀的静态内容,所以我们就会想到通过请求方式来判断,在程序中获取用户的请求方式,从而达到目的
但是上面的方式是有问题的,而且这个问题只有在生产环境草会被发现:
由于生产环境的证书是配置在nginx服务器上的,所以https只会到达nginx,nginx转发到我们web服务器的时候依旧是http请求,所以这种方式在生产环境始终是http的
所以推荐的解决方案就是配置静态地址的时候不要加上协议头,src可以直接写成"//res.rongzi.com....."这样浏览器就会根据具体的请求来识别使用哪种协议
5)关于HttpClient
目前我们项目里面的代码都习惯于使用using(HttpClient client = new HttpClient){}
但是这么写是有问题的:
1、就是HttpClient自己本身会维护一个连接池,所以说其实这个HttpClient只要实例化一个即可满足所有要求
2、以上调用方法使用完成会调用client的DIspose方法来释放这个池子,但是呢,这个池子的完全释放需要4分钟左右的时间,所以呢,这个会导致一个问题,就是这个如果4分钟之内请求到达 一定程度就会耗尽套接字,从而抛出一个异常(主站曾经出现过这样的问题)
具体文章链接:
所以针对这种情况我封装了一个HttpHelper的类来处理请求:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Platform.Facilitys
{
    public static class HttpHelper
    {
        

        static readonly HttpClient _client;
        static HttpHelper()
        {
            _client = new HttpClient();
        }
        
        public static TOut PostSync(ApiHost host, TIn postData)
           where TIn : class
           where TOut : class
        {
            var uri = new Uri(host.Domain);
            var url = new Uri(uri, host.ApiName);
            var response = _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData),Encoding.UTF8,host.DataMimeType)).Result;
            response.EnsureSuccessStatusCode();
            return response.Content.DesObj();

        }

        public static Task PostAsync(ApiHost host, TIn postData)
           where TIn : class
           where TOut : class
        {
            var uri = new Uri(host.Domain);
            var url = new Uri(uri, host.ApiName);
            return _client.PostAsync(url, new StringContent(JsonConvert.SerializeObject(postData), Encoding.UTF8, host.DataMimeType)).GetResult();
        }

        public static Task GetAsync(ApiHost host)
           where TOut : class
        {
            var uri = new Uri(host.Domain);
            var url = new Uri(uri, host.ApiName);
            return _client.GetAsync(url).GetResult();
        }

        static Task GetResult(this Task tsk)
           where TOut : class
        {
            return tsk.ContinueWith(
                res =>
                {
                    return res
                            .Result
                            .EnsureSuccessStatusCode()
                            .Content
                            .DesObj();
                }, TaskContinuationOptions.OnlyOnRanToCompletion);
        }

        static TOut DesObj(this HttpContent content)
           where TOut : class
        {
            var strJson = content.ReadAsStringAsync().Result;
            if (!string.IsNullOrWhiteSpace(strJson))
            {
                if (strJson.IndexOf("k__BackingField") > 0)
                {
                    DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(TOut));
                    using (var mStream = new MemoryStream(Encoding.Default.GetBytes(strJson)))
                    {
                        return ser.ReadObject(mStream) as TOut;
                    }

                }
                else
                {
                    return JsonConvert.DeserializeObject(strJson);
                }
            }
            return default(TOut);
        }
    }


    /// 
    /// WebApi配置
    /// 
    public class ApiHost
    {
        #region
        public ApiHost()
        {
            DataMimeType = "application/json";
        }
        public ApiHost(string domain, string apiName, string inputQueryString, string dataMimeType)
        {
            Domain = domain;
            ApiName = apiName;
            InputQueryString = inputQueryString;
            DataMimeType = dataMimeType;
        }
        #endregion
        #region
        /// 
        /// 主域名(比如http://api.rongzi.com or http://127.0.0.1)
        /// 
        public string Domain { get; set; }

        /// 
        /// Api名称(api/v1/studentinfotest)
        /// 
        public string ApiName { get; set; }

        /// 
        /// 传入参数名称
        /// 
        public string InputQueryString { get; set; }

        /// 
        /// 返回数据类型
        /// 
        public string DataMimeType { get; set; }

        /// 
        /// 重写ToString()
        /// 
        /// 
        public override string ToString()
        {
            return string.Format("{0}|{1}|{2}|{3}",
                this.ApiName,
                this.Domain,
                this.DataMimeType,
                this.InputQueryString);
        }
        #endregion
    }

}

 

HttpHelper.cs
6)关于线程存储
我们在开发的过程中,有时候在一个web生命周期内会需要从前到后传递一些对象之类的东西,这个时候可能会用到一个手段CallContext.SetData来设置数据,这个方法是将内容存放到线程中,所以只要在同一个线程中都可以取到这个内容,但是如果这个Action是异步的,async的,就会导致会有多个线程依次处理这个请求,这种情况往往是取不到之前设置的值的,这时候就可以使用CallContext.LogicSetData来设置值,这种方式设置的内容会被拷贝到新线程中