using RFrameGenerate.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace System.Web.Mvc
{
    /// <summary>
    /// 异常处理
    /// </summary>
    public class MvcExceptionLogAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            string message = "url:" + filterContext.HttpContext.Request.Url.ToString() + string.Format(",Type：{0},Message：{1},TargetSite：{2},Source：{3},controller：{4},action：{5}"
                , filterContext.Exception.GetType().Name
                , filterContext.Exception.Message
                , filterContext.Exception.TargetSite
                , filterContext.Exception.Source
                , filterContext.RouteData.GetRequiredString("controller")
                , filterContext.RouteData.GetRequiredString("action"));

            string ip = GetIP(filterContext.HttpContext.Request);

            MvcLog.Write(string.Format("IP:{0},OpenID:{1},message:",ip,OpenIDManage.GetOpenID()) + message);

            if (filterContext.HttpContext.Request.Url.ToString().Contains(".shop.") == true || filterContext.HttpContext.Request.Url.ToString().Contains("localhost:"))
                filterContext.Result = new ErrorResult("页面出错了");//微信端
            else
                filterContext.Result = new RedirectResult(RFrameGenerate.Common.CurrentManage.Domain + "error/index");//pc

            filterContext.ExceptionHandled = true;
           
        }

        protected string GetIP(HttpRequestBase request)
        {
            string ip = string.Empty;
            if (!string.IsNullOrEmpty(request.ServerVariables["HTTP_VIA"]))
                ip = Convert.ToString(request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
            if (string.IsNullOrEmpty(ip))
                ip = Convert.ToString(request.ServerVariables["REMOTE_ADDR"]);
            return ip;
        }
    }
}