private JsonResult Json <T>(string errorCode, string errorMessage, T result)
        {
            var error = new ErrorDescriber {
                Code = errorCode, Description = errorMessage
            };

            return(Json(WebApiResponse.Fail(error, result)));
        }
        protected JsonResult Fail(string errorCode, string errorMessage)
        {
            var error = new ErrorDescriber {
                Code = errorCode, Description = errorMessage
            };

            return(Json(WebApiResponse.Fail(error)));
        }
 protected JsonResult Json(IEnumerable <SimplyResult> results)
 {
     return(Json(results.Select(r => r.IsSuccess
         ? WebApiResponse.Ok()
         : WebApiResponse.Fail(new ErrorDescriber {
         Code = r.ErrorCode, Description = r.ErrorMessage
     }))));
 }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            if (context.Exception != null)
            {
                System.Net.HttpStatusCode defaultStatus = System.Net.HttpStatusCode.InternalServerError;
                WebApiResponse            response      = new WebApiResponse();
                System.Net.HttpStatusCode status        = defaultStatus;

                if (context.Exception is WebApiException webApiException)
                {
                    status   = (System.Net.HttpStatusCode)webApiException.Status;
                    response = response.Fail((System.Net.HttpStatusCode)webApiException.Status);
                }
                else if (context.Exception is System.UnauthorizedAccessException unauthorizedException)
                {
                    status = System.Net.HttpStatusCode.Unauthorized;
                }

                string message = "";

                if (System.String.IsNullOrEmpty(message))
                {
                    message = (System.String.IsNullOrEmpty(context.Exception.Message)) ? status.ToString() : context.Exception.Message;
                }

                response = new WebApiResponse().Fail(status).SetMessage(message);

                context.Result = new ObjectResult(response)
                {
                    StatusCode = (int)status
                };

                _logger.LogError(context.Exception, "Exception capturada en filtro");

                context.ExceptionHandled = true;
            }
        }
Beispiel #5
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                // 使用https
                options.Filters.Add(new RequireHttpsAttribute());
                options.Filters.Add(new WebApiExceptionFilter());
            }).AddJsonOptions(options =>
            {
                options.UseCamelCasing(true);
                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Unspecified;
                options.SerializerSettings.DateFormatString     = MyConstants.DateTimeFormatter.HyphenLongDateTime;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Latest)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = actionContext =>
                {
                    var errorMessage = string.Join(",", actionContext.ModelState.Values
                                                   .SelectMany(ms => ms.Errors
                                                               .Where(e => !string.IsNullOrEmpty(e.ErrorMessage) || e.Exception != null)
                                                               .Select(e => string.IsNullOrEmpty(e.ErrorMessage) ? e.Exception.Message : e.ErrorMessage)));

                    var error = new ErrorDescriber {
                        Code = HttpStatusCode.BadRequest.ToString(), Description = errorMessage
                    };
                    return(new JsonResult(WebApiResponse.Fail(error)));
                };
            });

            m_LoggerFactory.AddConsole();
            services.AddSingleton(m_LoggerFactory.CreateLogger("Lys.NetCore.Root"));

            services.AddResponseCompression();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddDbContextPool <MyDbContext>(opt => opt.UseSqlServer(m_Configuration.GetConnectionString("Default")));

            services.AddMemoryCache();

            var apiScope = m_Configuration["IdentityServer:ApiScope"];

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title   = "MyWebAPI"
                });

                options.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type     = "oauth2",
                    Flow     = "application",
                    TokenUrl = m_Configuration["IdentityServer:TokenUrl"],
                    Scopes   = new Dictionary <string, string>
                    {
                        // 供Swagger验证界面选择
                        { apiScope, "可访问的API" }
                    }
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "oauth2", new[] { apiScope } }
                });

                options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "Lys.NetCore.Portal.xml"));

                options.OperationFilter <ExamplesOperationFilter>();

                options.IgnoreObsoleteActions();
                options.IgnoreObsoleteProperties();
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(apiScope, policyAdmin => { policyAdmin.RequireClaim("scope", apiScope); });
            });

            services.AddAuthentication(options =>
            {
                options.DefaultScheme             = IdentityServerAuthenticationDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            })
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = m_Configuration["IdentityServer:Authority"];
                options.ApiName              = m_Configuration["IdentityServer:ApiName"];
                options.ApiSecret            = m_Configuration["IdentityServer:ApiSecret"];
                options.RequireHttpsMetadata = false;
            });

            ConfigureInfrastructureProject(services);
            ConfigureServiceProject(services);
            ConfigureAutoMapper(services);

            return(ConfigureServiceProvider(services));
        }