public Ret <Entity> ExecuteAndRenderResult(HttpContext httpContext) { var action = (string)httpContext.Request.Query["action"]; if (string.IsNullOrWhiteSpace(action)) { var self = httpContext.Request.GetRequestUri(); var entity = HttpEntity.Create(self, HttpStatusCode.BadRequest, $"Nenhuma ação foi indicada. Faltou definir o parâmetro \"action\"?" ); return(entity); } var method = PaperType.GetMethodIgnoreCase(action); if (method == null) { var self = httpContext.Request.GetRequestUri(); var entity = HttpEntity.Create(self, HttpStatusCode.NotImplemented, $"A ação solicitada não está disponível: \"{action}\"" ); return(entity); } return(ExecuteMethod(httpContext, method)); }
private async Task WriteAsync(Request req, Response res, HttpStatusCode status, string message, Exception ex) { try { if (message == null) { message = ex?.Message ?? status.ToString().ChangeCase(TextCase.ProperCase); } var validMimeTypes = new[] { MediaSerializer.JsonSiren, MediaSerializer.Json, MediaSerializer.XmlSiren, MediaSerializer.Xml }; var accept = new AcceptHeader(req.Headers, req.QueryArgs); var encoding = accept.BestEncoding; var mimeType = accept.SelectBestMatch(accept.MimeTypes, validMimeTypes) ?? MediaSerializer.Json; var renderType = mimeType.Contains("json") ? MediaSerializer.JsonSiren : MediaSerializer.XmlSiren; var serializer = new MediaSerializer(renderType); using (var memory = new MemoryStream()) { var entity = (ex != null) ? HttpEntity.Create(req.RequestUri, status, message, ex) : HttpEntity.Create(req.RequestUri, status, message); serializer.Serialize(entity, memory, encoding); memory.Position = 0; res.Status = status; res.Headers[HeaderNames.ContentType] = $"{mimeType}; charset={encoding.WebName}"; await memory.CopyToAsync(res.Body); } } catch (Exception exx) { res.Status = status; res.Headers[HeaderNames.ContentType] = $"text/plain; charset=UTF-8"; var ln = Environment.NewLine; var description = status.ToString().ChangeCase(TextCase.ProperCase); var writer = new StreamWriter(res.Body, Encoding.UTF8, bufferSize: 8 * 1024, leaveOpen: true); await writer.WriteAsync( $"{(int)status} - {description}{ln}{message}{ln}Fault:{ln}{exx.GetStackTrace()}{ln}Caused by:{ln}{ex.GetStackTrace()}" ); } }
public static async Task <Entity> RequestEntityAsync(string href) { try { await Task.Delay(3000); throw new NotImplementedException(nameof(RequestEntityAsync)); //return await Task.FromResult(new Entity()); } catch (Exception ex) { return(await Task.FromResult(HttpEntity.Create(href, ex))); } }
public static IPage CreatePage(Window window, Entity entity) { try { var @class = entity.Class?.OrderByDescending(Classes.IndexOf).FirstOrDefault(); var typeName = $"{typeof(IPage).Namespace}.{@class.ChangeCase(TextCase.PascalCase)}Page"; var type = Type.GetType(typeName) ?? typeof(ErrorPage); var page = (IPage)Activator.CreateInstance(type, window, entity); return(page); } catch (Exception ex) { string href = entity.Links?.FirstOrDefault(x => x.Rel.Has(RelNames.Self))?.Href; entity = HttpEntity.Create(href, ex); var page = new ErrorPage(window, entity); return(page); } }
public async Task <Ret <Content> > RequestAsync(string uri, string method, Entity data) { Ret <Content> ret; try { var http = new HttpClient(); ret = await http.RequestAsync(uri, method, data); } catch (Exception ex) { var fault = HttpEntity.Create(uri, ex); ret = Ret.Fail(uri, ex); ret.Value = new Content { Href = uri, Data = fault.Value }; } return(ret); }
public async Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider) { Entity entity = null; int status; try { var target = RenderTarget(httpContext); if (target?.Value is Uri uri) { // Redirecionando para outra URI httpContext.Response.StatusCode = (int)HttpStatusCode.Found; httpContext.Response.Headers[HeaderNames.Location] = uri.ToString(); return; } entity = target?.Value as Entity; if (entity == null) { var requestUri = httpContext.Request.GetDisplayUrl(); entity = HttpEntity.Create(requestUri, HttpStatusCode.NotFound); } status = (int)HttpStatusCode.OK; } catch (Exception ex) { ex.Trace(); entity = HttpEntity.Create(httpContext.Request.GetDisplayUrl(), ex); status = (int)HttpStatusCode.InternalServerError; } try { var mediaType = httpContext.Request.ContentType?.Contains("xml") == true ? "application/xml" : "application/json"; var serializer = new MediaSerializer(); var content = serializer.Serialize(entity, mediaType); httpContext.Response.StatusCode = (int)status; httpContext.Response.ContentType = $"{mediaType}; charset=UTF-8"; await httpContext.Response.WriteAsync(content); } catch (Exception ex) { ex.Trace(); status = (int)HttpStatusCode.InternalServerError; var statusDecription = HttpStatusCode.InternalServerError .ToString() .ChangeCase(TextCase.ProperCase); httpContext.Response.StatusCode = status; httpContext.Response.ContentType = $"text/plain; charset=UTF-8"; var nl = Environment.NewLine; var cause = string.Join(nl, ex.GetCauseMessages().Select(x => $" • {x}")); var message = $"Fault {nl} {status} - {statusDecription} {nl}Cause {nl}{cause}"; await httpContext.Response.WriteAsync(message); } }
private async Task SendProxyAsync(HttpContext httpContext) { var req = httpContext.Request; var query = httpContext.Request.Query; var path = (string)query["path"]; if (path != null) { Proxy proxy = registry.FindExact(path); if (proxy == null) { var ret = HttpEntity.Create( route: req.GetRequestUri(), status: HttpStatusCode.NotFound, message: $"Proxy não registrado: {path}" ); await SendStatusAsync(httpContext, ret); } else { var href = req.GetRequestUri(); var allProxiesHref = new Route(href).UnsetArgs("path"); var entity = new Entity(); entity.Title = $"Configuração de proxy: {proxy.Path}"; entity.Class = KnownClasses.Single; entity.Links = new LinkCollection(); entity.Links.AddSelf(href); entity.Links.Add("link", "Todas as configurações de proxy", allProxiesHref); entity.Properties = new PropertyCollection(); entity.Properties.AddFromGraph(proxy); entity.Properties.AddDataHeadersFromGraph <Proxy>(); await SendStatusAsync(httpContext, Ret.Ok(entity)); } } else { var entity = new Entity(); entity.Class = KnownClasses.Rows; entity.Title = "Todas as configurações de proxy"; entity.Links = new LinkCollection(); entity.Links.AddSelf(req.GetRequestUri()); entity.Entities = new EntityCollection(); entity.Properties = new PropertyCollection(); entity.Properties.AddRowsHeadersFromGraph <Proxy>(); foreach (var knownPath in registry.Paths) { var proxy = registry.FindExact(knownPath); var href = new Route(req.GetRequestUri()) .SetArg("path", proxy.Path) .ToString(); var row = new Entity(); row.Title = $"Configuração de proxy: {proxy.Path}"; row.Class = KnownClasses.Row; row.Rel = KnownRelations.Row; row.Links = new LinkCollection(); row.Links.AddSelf(href); row.Properties = new PropertyCollection(); row.Properties.AddFromGraph(proxy); entity.Entities.Add(row); } await SendStatusAsync(httpContext, Ret.Ok(entity)); } }
private async Task EditProxyAsync(HttpContext httpContext) { var req = httpContext.Request; var query = httpContext.Request.Query; var path = (string)query["path"]; var reverseUri = (string)query["reverseUri"]; if (path == null || reverseUri == null) { var ret = HttpEntity.Create( route: req.GetRequestUri(), status: HttpStatusCode.BadRequest, message: "Uso incorreto. Os parâmetros `path' e `reverseUri' devem ser indicados." ); await SendStatusAsync(httpContext, ret); return; } bool hasDelete = req.Method.EqualsAny("DELETE", "PUT", "PATCH"); bool hasEdit = req.Method.EqualsAny("GET", "POST", "PUT", "PATCH"); Proxy oldProxy = registry.FindExact(path); Proxy newProxy; try { newProxy = Proxy.Create(path, reverseUri); } catch (Exception ex) { ex.TraceWarning(); var ret = HttpEntity.Create( route: req.GetRequestUri(), status: HttpStatusCode.BadRequest, message: "Os parâmetros `path' e `reverseUri` não estão corretos." ); await SendStatusAsync(httpContext, ret); return; } if (oldProxy != null && !oldProxy.ReverseUri.Equals(newProxy.ReverseUri)) { var ret = HttpEntity.Create( route: req.GetRequestUri(), status: HttpStatusCode.BadRequest, message: $"Já existe um proxy diferente configurado nesta rota `{oldProxy.Path}'." ); await SendStatusAsync(httpContext, ret); return; } if (hasDelete) { if (oldProxy != null) { registry.Remove(path); } } if (hasEdit) { if (oldProxy != null) { oldProxy.Enabled = true; oldProxy.LastSeen = DateTime.Now; } else { registry.Add(newProxy); } } var status = HttpEntity.Create( route: req.GetRequestUri(), status: HttpStatusCode.OK, message: hasEdit ? "Registro de proxy efetuado." : "Registro de proxy removido." ); status.Data.Properties.Add("Path", newProxy.Path.ToString()); status.Data.Properties.Add("ReverseUri", newProxy.ReverseUri.ToString()); await SendStatusAsync(httpContext, status); }
public static Entity GetStatus(UriString requestUri, string prefix) { return(HttpEntity.Create(requestUri, HttpStatusCode.OK)); }
private async Task <Ret <Content> > SendAsync( string uri , string method , object upData , string upType , string upCharset , string downType , string downCharset , int maxRedirect = 5 ) { try { #if DEBUG if (upData is Entity upEntity) { Debug.WriteLine("---REQUEST---"); Debug.WriteLine(upEntity.ToJson()); Debug.WriteLine("---END---"); } #endif var ret = await http.RequestAsync(uri, method, upData, upType, upCharset, downType, downCharset); var isRedirect = (ret.Status.CodeClass == HttpStatusClass.Redirection) && (maxRedirect > 0); if (isRedirect) { var redirectUri = ret.Status.Headers[HeaderNames.Location] ?? uri; switch (ret.Status.Code) { case HttpStatusCode.Redirect: { return(await SendAsync( redirectUri , MethodNames.Get , upData : null , upType : null , upCharset : null , downType : downType , downCharset : downCharset , maxRedirect : maxRedirect - 1 )); } case HttpStatusCode.RedirectKeepVerb: { return(await SendAsync( redirectUri , method , upData , upType , upCharset , downType , downCharset , maxRedirect - 1 )); } } } #if DEBUG if (ret.Value?.Data is Entity downEntity) { Debug.WriteLine("---RESPONSE---"); Debug.WriteLine(downEntity.ToJson()); Debug.WriteLine("---END---"); } #endif if (ret.Value?.Data == null) { var faultEntity = HttpEntity.CreateFromRet(uri, ret); ret.Value = new Content { Href = uri, Data = faultEntity.Value }; } return(ret); } catch (Exception ex) { var faultEntity = HttpEntity.Create(uri, ex); return(new Ret <Content> { Status = faultEntity.Status, Fault = faultEntity.Fault, Value = new Content { Href = uri, Data = faultEntity.Value } }); } }