What's the right way to have a contextual link on controller action?
I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

function mymodule_theme() {
  return [
    'mymodule' =&gt; [
      'template' =&gt; 'mymodule',
      'variables' =&gt; [              //Added a variable content
        'content' =&gt; '',
      ]
    ],
  ];
}


File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule' 


File : IndexController.php

public function index() {
    $data['content'] = [
        '#type' =&gt; 'markup',
        '#markup' =&gt; $this-&gt;t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' =&gt; [
            'route_parameters' =&gt; [],
        ],
    ];

    return [
        '#theme' =&gt; 'mymodule',
        '#content' =&gt; $data,        //Pass Contextual link to the variable
    ];
}


File : mymodule.html.twig

{%
set classes = [
'contextual-region'
]
%}

&lt;div {{ attributes.addClass(classes) }}&gt;
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
&lt;/div&gt;


--

Thanks