question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Custom HttpRequest

See original GitHub issue

Trying customize HttpRequest.

I’ve followed directions from: first: https://github.com/elsa-workflows/elsa-core/issues/1393 then: https://github.com/tomy2105/elsa-core/blob/test/HTTPEndpointExtension/src/samples/dashboard/aspnetcore/ElsaDashboard.Samples.AspNetCore.Monolith/TestReceiveRequest.cs

Following these, I’ve then implemented my HttpRequestEx, but no way it gets reached by an request via postman (it returns NotFound).

After too many tries and errors, I decided to sniff the code, then I found that in HttpEndpointMiddleware.cs, line 81, there is something hardcoded:

//my note: hardcoded!
const string activityType = nameof(HttpEndpoint);

If I change that to:

const string activityType = nameof(HttpEndpointEx);

the route now works fine.

So I’m left with two doubts, is it happening because I am still doing something wrong in my code or is it necessary to rewrite the HttpEndpointMiddleware to know my HttpRequestEx?

Here is the code for my HttpRequestEx just in case:


    [Trigger(
    Category = "HTTP",
    DisplayName = "HTTP Endpoint EX",
    Description = "Handle an incoming HTTP request (extended).",
    Outcomes = new[] { OutcomeNames.Done }
    )]
    public class HttpEndpointEx : HttpEndpoint
    {
        private readonly IHttpContextAccessor httpContextAccessor;

        [ActivityInput(
        Hint = "Additional headers to write.",
        UIHint = ActivityInputUIHints.MultiLine,
        DefaultSyntax = SyntaxNames.Json,
        SupportedSyntaxes = new[] { SyntaxNames.JavaScript, SyntaxNames.Liquid, SyntaxNames.Json },
        Category = PropertyCategories.Advanced
        )]
        public HttpResponseHeaders ResponseHeaders { get; set; }



        public HttpEndpointEx(IHttpContextAccessor httpContextAccessor)
        {
            this.httpContextAccessor = httpContextAccessor;
        }

        
        protected override IActivityExecutionResult OnExecute()
        {
            var httpContext = httpContextAccessor.HttpContext ?? new DefaultHttpContext();
            var response = httpContext.Response;

            if (response.HasStarted)
                return Fault("Response has already started");

            var headers = ResponseHeaders;
            if (headers != null)
            {
                foreach (var header in headers)
                    response.Headers[header.Key] = header.Value;
            }

            return base.OnExecute();
        }

        ///// <summary>
        ///// didn't work!
        ///// </summary>
        //public override string Type => nameof(HttpEndpoint);
    }

    /// <summary>
    /// Added this to Startup.cs => services.AddBookmarkProvider<HttpEndpointExBookmarkProvider>();
    /// </summary>
    public class HttpEndpointExBookmarkProvider : BookmarkProvider<HttpEndpointExBookmark, HttpEndpointEx>
    {
        public override bool SupportsActivity(BookmarkProviderContext<HttpEndpointEx> context)
        {
            return context.ActivityType.TypeName == nameof(HttpEndpointEx);
        }

        public override async ValueTask<IEnumerable<BookmarkResult>> GetBookmarksAsync(BookmarkProviderContext<HttpEndpointEx> context, CancellationToken cancellationToken)
        {
            var path = ToLower((await context.ReadActivityPropertyAsync(x => x.Path, cancellationToken))!);
            var methods = (await context.ReadActivityPropertyAsync(x => x.Methods, cancellationToken))?.Select(ToLower) ?? Enumerable.Empty<string>();
            BookmarkResult CreateBookmark(string method) => Result(new(path, method));
            return methods.Select(CreateBookmark);
        }

        private static string ToLower(string s) => s.ToLowerInvariant();
    }

    public record HttpEndpointExBookmark(string Path, string? Method) : IBookmark;

Edit: it seems the problem is related to zero instances saved + HttpEndpointEx as the first activity. I’ve done a late test and when there are instances saved, the middleware is able to retrieve the instances :S

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:15 (11 by maintainers)

github_iconTop GitHub Comments

2reactions
cristinamuduracommented, Jul 26, 2022

@avataron Not sure if this is what you need but… :

If you want to customise some things in a specific activity, what you can do basically is to implement a notification handler that listens to INotificationHandler<DescribingActivityType>. Then you can basically verify the type of activity and implement custom logic like hiding properties etc ( that’s more on the UI level).

        public Task Handle(DescribingActivityType notification, CancellationToken cancellationToken)
        {
            var activityType = notification.ActivityType;

            if (activityType.Type == typeof(HttpEndpoint))
            {
                var inputProps = notification.ActivityDescriptor.InputProperties;
               // here you can hide properties or add new ones etc
            }
            return Task.CompletedTask;
        }

If you want to implement custom logic for specific defined properties ( like settings always some headers ) you can implement the notification handler of activityexecuting (INotificationHandler<ActivityExecuting>)

        public Task Handle(ActivityExecuting notification, CancellationToken cancellationToken)
        {
            var activityType = notification.Activity;

            if (activityType is HttpEndpoint)
            {
                var httpEndpoint = activityType as HttpEndpoint;

                httpEndpoint.Output.Headers.Add("My-Header", "value");
            }

            return Task.CompletedTask;
        }
2reactions
tomy2105commented, Jul 25, 2022

@mohdali I don’t know what was @avataron 's use case. My use case was that I wanted to hide (hardcode, something) some of the properties of the HTTPEndpoint activity to make it simpler for my users (for example, it always accepts only post requests, always reads body, the type of the object it reads from body is fixed, etc…)

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to compose a HTTP request with a custom ...
I need to request ressources which are bound to custom HTTP methods on server side. I know about the fire fox plugin RESTClient...
Read more >
Creating a custom request handler
This guide covers how to write a custom httpRequest handler script. # Step 1: create the request. var request = new httpRequest(). #...
Read more >
Custom HTTP Header With the Java HttpClient
We can easily add custom headers using one of three methods from the HttpRequest.Builder object: header, headers, or setHeader.
Read more >
HTTP Request Headers
Custom request headers. You can set up your pages so that a custom request header is sent with every request that's made while...
Read more >
How do I send GET Request with Custom Headers?
To send a GET request with custom HTTP headers, you must provide custom headers in the "Name: Value" format, just like the standard...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found