Beispiel #1
0
        /// <summary>
        /// 获取文本返回
        /// </summary>
        /// <param name="actionResult"></param>
        /// <returns></returns>
        protected virtual IFullHttpResponse GetTextResponse(object actionResult)
        {
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders("text/plain;charset=utf-8");
            IFullHttpResponse result = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, actionResult.ToString(), headers);

            return(result);
        }
        public IFullHttpResponse HandlerException(IByteBufferHolder byteBufferHolder, Exception exception)
        {
            ConsoleHelper.ServerWriteError(exception);
            ResultModel resultModel = ResultModel.Fail("服务器错误,请联系后端工程师");

            return(HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, resultModel.ToJson()));
        }
Beispiel #3
0
        /// <summary>
        /// 获得文件返回
        /// </summary>
        /// <param name="url"></param>
        /// <param name="IfModifiedSince"></param>
        /// <returns></returns>
        protected virtual async Task <IFullHttpResponse> GetFileResponseAsync(string url, ICharSequence IfModifiedSince)
        {
            if (url.StartsWith("/") || url.StartsWith(@"\"))
            {
                url = url.Substring(1);
            }
            string filePath  = Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? throw new DotNettyException("路径为空"), HtmlPageFolderPath, url);
            string extension = Path.GetExtension(filePath);

            if (string.IsNullOrEmpty(extension))
            {
                return(HttpResponseHelper.GetHttpResponse(HttpResponseStatus.NotFound));
            }
            if (!File.Exists(filePath))
            {
                return(HttpResponseHelper.GetHttpResponse(HttpResponseStatus.NotFound));
            }
            (FileCacheModel fileCacheModel, bool isCache) = await GetFileBytesAsync(filePath, IfModifiedSince);

            string contentType = MIMEManager.GetContentType(extension);
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders(contentType);

            headers.Add(HttpHeaderNames.LastModified, fileCacheModel.CacheTime);
            if (isCache)
            {
                return(HttpResponseHelper.GetHttpResponse(HttpResponseStatus.NotModified, headers));
            }
            headers.Add(HttpHeaderNames.Expires, DateTime.Now.AddSeconds(CacheSecond));
            headers.Add(HttpHeaderNames.CacheControl, $"max-age={CacheSecond}");
            return(HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, fileCacheModel.Body, headers));
        }
Beispiel #4
0
        /// <summary>
        /// 处理Action过滤器
        /// </summary>
        /// <param name="request"></param>
        /// <param name="globalFilters"></param>
        /// <returns></returns>
        public async Task <IFullHttpResponse> HandlerActionBeforeFilterAsync(IFullHttpRequest request, params IFilter[] globalFilters)
        {
            IFullHttpResponse          response   = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK);
            List <Attribute>           attributes = Action.GetCustomAttributes().ToList();
            List <IActionBeforeFilter> filters    = attributes.OfType <IActionBeforeFilter>().ToList();

            if (globalFilters != null && globalFilters.Length > 0)
            {
                filters.AddRange(globalFilters.OfType <IActionBeforeFilter>());
            }
            foreach (IActionBeforeFilter filter in filters)
            {
                filter.HandlerFilter(BaseController, this, request, ref response);
                if (response.Status.Code != HttpResponseStatus.OK.Code)
                {
                    return(response);
                }
            }
            List <IActionBeforeAsyncFilter> asyncFilters = attributes.OfType <IActionBeforeAsyncFilter>().ToList();

            if (globalFilters != null && globalFilters.Length > 0)
            {
                asyncFilters.AddRange(globalFilters.OfType <IActionBeforeAsyncFilter>());
            }
            foreach (IActionBeforeAsyncFilter filter in asyncFilters)
            {
                await filter.HandlerFilterAsync(BaseController, this, request, ref response);

                if (response.Status.Code != HttpResponseStatus.OK.Code)
                {
                    return(response);
                }
            }
            return(response);
        }
Beispiel #5
0
        /// <summary>
        /// 获取Json返回
        /// </summary>
        /// <param name="actionResult"></param>
        /// <returns></returns>
        protected virtual IFullHttpResponse GetJsonResponse(object actionResult)
        {
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders("application/json;charset=utf-8");
            IFullHttpResponse result = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, actionResult.ToJson(), headers);

            return(result);
        }
Beispiel #6
0
        /// <summary>
        /// 获得Response
        /// </summary>
        /// <param name="baseController"></param>
        /// <param name="action"></param>
        /// <param name="params"></param>
        /// <returns></returns>
        protected virtual async Task <IFullHttpResponse> GetResponseAsync(BaseController baseController, ActionInfo action, object[] @params)
        {
            object actionResult = action.Action.Invoke(baseController, @params);

            if (actionResult is Task task)
            {
                dynamic taskObj = task;
                actionResult = await taskObj;
            }
            IFullHttpResponse result;

            if (actionResult != null)
            {
                if (actionResult is Stream stream)
                {
                    result = await GetStreamResponseAsync(stream);
                }
                else if (actionResult.GetType().IsClass&& !(actionResult is string))
                {
                    result = GetJsonResponse(actionResult);
                }
                else
                {
                    result = GetTextResponse(actionResult);
                }
            }
            else
            {
                result = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK);
            }
            return(result);
        }
Beispiel #7
0
        /// <summary>
        /// 处理Body和Url参数
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parameters"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        protected virtual object[] HandlerBodyAndUrlParams(IFullHttpRequest request, IReadOnlyList <ParameterInfo> parameters, ref IFullHttpResponse response)
        {
            string bodyParams = GetBodyParams(request);
            Dictionary <string, string> urlParams = GetUrlParams(request);

            if (parameters.Count <= 0)
            {
                return(null);
            }
            var @params = new object[parameters.Count];

            for (var i = 0; i < parameters.Count; i++)
            {
                if (!string.IsNullOrEmpty(bodyParams) && parameters[i].ParameterType.IsClass && parameters[i].ParameterType != typeof(string))
                {
                    @params[i] = bodyParams.JsonToObject(parameters[i].ParameterType);
                    continue;
                }
                if (urlParams.ContainsKey(parameters[i].Name ?? throw new MateralDotNettyException("参数为空")))
                {
                    @params[i] = urlParams[parameters[i].Name].ConvertTo(parameters[i].ParameterType);
                    continue;
                }
                if (@params[i] == null)
                {
                    ResultModel resultModel = ResultModel.Fail($"参数{parameters[i].Name}错误");
                    response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.BadRequest, resultModel.ToJson());
                    return(null);
                }
            }
            return(@params);
        }
Beispiel #8
0
        /// <summary>
        /// 处理HttpMethodAttribute
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public IFullHttpResponse HandlerMethod(IFullHttpRequest request)
        {
            IFullHttpResponse response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK);
            var attribute = Action.GetCustomAttribute <HttpMethodAttribute>();

            attribute?.Handler(request, response);
            return(response);
        }
Beispiel #9
0
        /// <summary>
        /// 获得Options返回
        /// </summary>
        /// <param name="methodName"></param>
        /// <returns></returns>
        protected virtual IFullHttpResponse GetOptionsResponse(string methodName)
        {
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders();

            headers.Add(HttpHeaderNames.AccessControlAllowHeaders, "authorization,access-control-allow-origin,content-type");
            headers.Add(HttpHeaderNames.AccessControlAllowMethods, $"{methodName.ToUpper()}");
            IFullHttpResponse response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, headers);

            return(response);
        }
Beispiel #10
0
        /// <summary>
        /// 获取流返回
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        protected virtual async Task <IFullHttpResponse> GetStreamResponseAsync(Stream stream)
        {
            var bytes = new byte[stream.Length];
            await stream.ReadAsync(bytes, 0, bytes.Length);

            stream.Close();
            stream.Dispose();
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders("application/octet-stream");
            IFullHttpResponse result = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK, bytes, headers);

            return(result);
        }
Beispiel #11
0
        /// <summary>
        /// 处理FormData
        /// </summary>
        /// <param name="request"></param>
        /// <param name="parameters"></param>
        /// <param name="response"></param>
        /// <returns></returns>
        protected virtual object[] HandlerFormDataParams(IFullHttpRequest request, IReadOnlyList <ParameterInfo> parameters, ref IFullHttpResponse response)
        {
            if (parameters.Count == 1 && parameters[0].ParameterType == typeof(IUploadFileModel))
            {
                var @params = new object[parameters.Count];
                @params[0] = new DefaultUploadFileModel(request);
                return(@params);
            }
            ResultModel resultModel = ResultModel.Fail("参数错误,multipart/form-data只能接收一个byte[]");

            response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.BadRequest, resultModel.ToJson());
            return(null);
        }
Beispiel #12
0
        /// <summary>
        /// 处理权限过滤器
        /// </summary>
        /// <param name="request"></param>
        /// <param name="globalFilters"></param>
        /// <returns></returns>
        public async Task <IFullHttpResponse> HandlerAuthorityFilterAsync(IFullHttpRequest request, params IFilter[] globalFilters)
        {
            Type controllerType         = BaseController.GetType();
            IFullHttpResponse response  = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.OK);
            var allowAuthorityAttribute = Action.GetCustomAttribute <AllowAuthorityAttribute>();

            if (allowAuthorityAttribute != null)
            {
                return(response);
            }
            allowAuthorityAttribute = controllerType.GetCustomAttribute <AllowAuthorityAttribute>();
            if (allowAuthorityAttribute != null)
            {
                return(response);
            }

            List <Attribute>        controllerAttributes = controllerType.GetCustomAttributes().ToList();
            List <Attribute>        actionAttributes     = Action.GetCustomAttributes().ToList();
            List <IAuthorityFilter> filters = actionAttributes.OfType <IAuthorityFilter>().ToList();

            filters.AddRange(controllerAttributes.OfType <IAuthorityFilter>());
            if (globalFilters != null && globalFilters.Length > 0)
            {
                filters.AddRange(globalFilters.OfType <IAuthorityFilter>());
            }
            foreach (IAuthorityFilter filter in filters)
            {
                filter.HandlerFilter(BaseController, this, request, ref response);
                if (response.Status.Code != HttpResponseStatus.OK.Code)
                {
                    return(response);
                }
            }
            List <IAuthorityAsyncFilter> asyncFilters = actionAttributes.OfType <IAuthorityAsyncFilter>().ToList();

            asyncFilters.AddRange(controllerAttributes.OfType <IAuthorityAsyncFilter>());
            if (globalFilters != null && globalFilters.Length > 0)
            {
                asyncFilters.AddRange(globalFilters.OfType <IAuthorityAsyncFilter>());
            }
            foreach (IAuthorityAsyncFilter filter in asyncFilters)
            {
                await filter.HandlerFilterAsync(BaseController, this, request, ref response);

                if (response.Status.Code != HttpResponseStatus.OK.Code)
                {
                    return(response);
                }
            }
            return(response);
        }
Beispiel #13
0
 public override async Task HandlerAsync(IChannelHandlerContext ctx, IByteBufferHolder byteBufferHolder)
 {
     try
     {
         await HandlerAsync <IFullHttpRequest>(ctx, byteBufferHolder, HandlerRequestAsync);
     }
     catch (Exception exception)
     {
         OnException?.Invoke(exception);
         Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders("text/plain;charset=utf-8");
         IFullHttpResponse response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.InternalServerError, exception.Message, headers);
         await SendHttpResponseAsync(ctx, byteBufferHolder, response);
     }
 }
Beispiel #14
0
        /// <summary>
        /// 处理请求
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        protected virtual async Task HandlerRequestAsync(IChannelHandlerContext ctx, IFullHttpRequest request)
        {
            IFullHttpResponse response = null;

            IFilter[] globalFilters = _controllerBus.GetGlobalFilters();
            if (!request.Uri.StartsWith("/api/"))
            {
                if (CanNext)
                {
                    return;
                }
                response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.NotFound);
            }
            else
            {
                string[] urls = request.Uri.Split('/');
                if (urls.Length < 4)
                {
                    return;
                }
                string controllerKey = urls[2];
                try
                {
                    BaseController baseController = _controllerBus.GetController(controllerKey);
                    baseController.Request = request;
                    string     actionKey = urls[3].Split('?')[0];
                    ActionInfo action    = baseController.GetAction(actionKey);
                    if (!HandlerOptions(ctx, request, action, ref response))
                    {
                        response = await baseController.HandlerControllerBeforeFilterAsync(globalFilters);

                        if (response.Status.Code == HttpResponseStatus.OK.Code)
                        {
                            response = await GetResponseAsync(request, baseController, action, globalFilters);

                            await baseController.HandlerControllerAfterFilterAsync(response, globalFilters);
                        }
                    }
                }
                catch (MateralDotNettyServerException exception)
                {
                    ResultModel resultModel = ResultModel.Fail(exception.Message);
                    response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.NotFound, resultModel.ToJson());
                }
            }
            await SendHttpResponseAsync(ctx, request, response);

            StopHandler();
        }
Beispiel #15
0
 public override void HandlerFilter(BaseController baseController, ActionInfo actionInfo, IFullHttpRequest request, ref IFullHttpResponse response)
 {
     if (!(baseController is MateralProjectBaseController materalProjectBaseController))
     {
         return;
     }
     try
     {
         Guid loginUserID = materalProjectBaseController.GetLoginUserID();
         if (loginUserID == Guid.Empty)
         {
             response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.Unauthorized);
         }
     }
     catch (MateralProjectException)
     {
         response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.Unauthorized);
     }
 }
Beispiel #16
0
        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="byteBufferHolder"></param>
        /// <param name="exception"></param>
        /// <returns></returns>
        protected virtual async Task HandlerExceptionAsync(IChannelHandlerContext ctx, IByteBufferHolder byteBufferHolder, Exception exception)
        {
            Dictionary <AsciiString, object> headers = HttpResponseHelper.GetDefaultHeaders("text/plain;charset=utf-8");
            IFullHttpResponse response = HttpResponseHelper.GetHttpResponse(HttpResponseStatus.InternalServerError, exception.Message, headers);

            IFilter[] globalFilters = _controllerBus.GetGlobalFilters();
            List <IExceptionFilter>      exceptionFilters      = globalFilters.OfType <IExceptionFilter>().ToList();
            List <IExceptionAsyncFilter> exceptionAsyncFilters = globalFilters.OfType <IExceptionAsyncFilter>().ToList();

            if (exceptionFilters.Count > 0 || exceptionAsyncFilters.Count > 0)
            {
                foreach (IExceptionFilter exceptionFilter in exceptionFilters)
                {
                    response = exceptionFilter.HandlerException(byteBufferHolder, exception);
                }
                foreach (IExceptionAsyncFilter exceptionFilter in exceptionAsyncFilters)
                {
                    response = await exceptionFilter.HandlerExceptionAsync(byteBufferHolder, exception);
                }
            }
            await SendHttpResponseAsync(ctx, byteBufferHolder, response);

            StopHandler();
        }