public async Task <ApiResponseBase> SaveBanner(string content, IFormFile file) { var result = new ApiResponseBase(); try { var bannerObj = _context.Banners.FirstOrDefault(); var webRootPath = _hostingEnvironment.WebRootPath; var tempPath = Path.Combine(webRootPath, @"img/content"); var imageURl = bannerObj?.ImageUrl ?? ""; if (file != null) { var extension = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"') .Split('.'); var fileExtension = extension[1]; var fileName = Guid.NewGuid() + "." + fileExtension; var fullPath = Path.Combine(tempPath, fileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } imageURl = "~/img/content/" + fileName; } if (bannerObj == null) { bannerObj = new Banner { Content = content, ImageUrl = imageURl, }; _context.Banners.Add(bannerObj); } else { bannerObj.Content = content; bannerObj.ImageUrl = imageURl; } _context.SaveChanges(); result.MakeTrue("Cập nhật thành công!"); } catch (Exception ex) { result.MakeException("Đã có lỗi xảy ra vui lòng thử lại" + ex.Message); } return(result); //return await DxGridHelper.HandleEdit<ProductType>(_context, reqPath, true); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.ConfigureExceptionHandler(new LogSystem()); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "API V1"); c.EnableFilter(); }); app.UseRouting(); app.Use(async(context, next) => { Endpoint endpoint = context.GetEndpoint(); if (endpoint != null) { var routePattern = (endpoint as Microsoft.AspNetCore.Routing.RouteEndpoint)?.RoutePattern?.RawText; await next(); } else { var res = new ApiResponseBase(); res.SetNotFoundResponse(context.Response, "Function not found"); context.Response.ContentType = "application/json; charset=utf-8"; await context.Response.WriteAsync(JsonConvert.SerializeObject(res)); } }); app.UseMiddleware <AuthAPIMiddleware>(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
public ApiResponseBase Search(MelissaSearchModel searchParams) { var result = new ApiResponseBase(); var searchResult = new SearchResult(); var data = string.Empty; try { FullContactResponse.RootObject detail = null; if (!string.IsNullOrEmpty(searchParams.Email)) { data = GetDataFromUrl(FullContactUrl + "/v2/person.json?email=" + searchParams.Email + "&apiKey=" + FullContactApiKey); } else if (!string.IsNullOrEmpty(searchParams.Phone)) { data = GetDataFromUrl(FullContactUrl + "/v2/person.json?phone=" + searchParams.Phone + "&apiKey=" + FullContactApiKey); } if (!string.IsNullOrEmpty(data)) { detail = JsonConvert.DeserializeObject <FullContactResponse.RootObject>(data, new JsonSerializerSettings { StringEscapeHandling = StringEscapeHandling.EscapeHtml }); searchResult.FullContact = detail; } if (detail != null) { var globalData = SearchGlobalemailMelissadataByMail(searchParams.Email); searchResult.GlobalemailMelissaData = globalData; searchResult.PersonatorMelissaData = SearchPersonatorMelissadataByMail(searchParams.Email); searchResult.CompanyFullContact = GetCompanyInfor($"{globalData.Records[0].DomainName}.{globalData.Records[0].TopLevelDomain}"); } result.Data = searchResult; } catch (Exception ex) { result.Errors.Add(ex.Message); } return(result); }
public async Task InvokeAsync(HttpContext context, IAuthTokenChecker authChecker, ILogFactory logFactory) { var token = context.Request.Headers["token"].ToString(); if (authChecker.IsValidToken(token)) { await _next.Invoke(context); return; } else { var res = new ApiResponseBase(); res.SetUnauthorizedResponse(context.Response, "Invalid token"); await context.Response.WriteAsync(JsonConvert.SerializeObject(res, new JsonSerializerSettings { Formatting = Formatting.Indented })); return; } }
public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILogFactory logFactory) { var logger = logFactory.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); app.UseExceptionHandler(appError => { appError.Run(async context => { context.Response.ContentType = "application/json"; var contextFeature = context.Features.Get <IExceptionHandlerFeature>(); if (contextFeature != null) { logger.Error($"Something went wrong: {contextFeature.Error}"); var res = new ApiResponseBase(); res.SetInternalErrorResponse(context.Response, "Internal Server Error." + contextFeature.Error.Message); await context.Response.WriteAsync(JsonConvert.SerializeObject(res)); } }); }); }
async public virtual Task <ActionResult> query([FromBody] QueryRequest request) { ActionResult result; List <Criteria> cri = new List <Criteria>(); if (request != null) { if (request.criterias != null) { foreach (var criteria in request.criterias) { cri.Add(new Criteria { Field = criteria.Field, Operator = criteria.Operator, Value = criteria.Value }); } } } else { request = new QueryRequest(); } List <T> rows = await _service.List <T>(cri, request.page.Value, request.size.Value); ApiResponseBase response = new ApiResponseBase() { success = true, data = rows, message = null, paginacao = await _service.totalLinhas <T>(request.size, cri) }; result = Ok(response); return(result); }
async public virtual Task <ActionResult> Delete(string id) { ActionResult result; try { T record = await findRecord(id); if (record == null) { result = NotFound(); } else { await _service.Delete(record); ApiResponseBase response = new ApiResponseBase() { success = true, data = null, message = null }; result = AcceptedAtAction(nameof(Delete), response); } } catch (Exception ex) { ApiResponseBase response = new ApiResponseBase() { success = false, data = null, message = ex.Message }; result = BadRequest(response); } return(result); }
async public virtual Task <ActionResult> Get(string id) { ActionResult result; try { T record = await findRecord(id); if (record == null) { result = NotFound(); } else { ApiResponseBase response = new ApiResponseBase() { success = true, data = record, message = null }; result = Ok(response); } } catch (Exception ex) { ApiResponseBase response = new ApiResponseBase() { success = false, data = null, message = ex.Message }; result = BadRequest(response); } return(result); }
public static void AssertErrorIsNull(ApiResponseBase response) { Console.WriteLine(response.CommandText); Assert.IsNull(response.Error, response.Error?.ToString() ?? "Makes Compiler Happy"); }
static async void RpcPostTest() { ApiResponseBase <User> response = await RpcHelper.PostAsync <LoginDto, ApiResponseBase <User> >("http://192.168.6.191:8086/api/Login/Login ", new LoginDto { LoginName = "hqmcq", LoginPwd = "123456" }); Console.WriteLine(response.ToJson()); }
public FreeboxException(ApiResponseBase response, HttpResponseMessage responseMessage) { Response = response; ResponseMessage = responseMessage; }
public static void AssertErrorIsNull(ApiResponseBase response) { Assert.IsNull(response.Error, response.Error?.ToString() ?? "Makes Complier Happy"); }