Skip to main content

Notifications

Power Automate - Connector Development
Unanswered

How to Make a Simple Custom Connector With Custom C# Code?

Like (1) ShareShare
ReportReport
Posted on 4 Oct 2024 18:12:46 by 4,768
Hello,

I want to learn how to create custom connectors that use the C# code component. I'm starting by trying to create a custom connector that doesn't really call any API, but instead just takes a single input like Name and then passes that Name parameter to the C# code to form & output a dynamic "Hello, {Name}" string.

So far even with chat gpt I'm having trouble. I've created the Request piece in the Definition stage with a required Name header / input. But I can't seem to get the C# code to properly pull that Name data in & add it to the string. How should the C# be set up? Do I have to also set up the Response in the Definition a certain way?
 
 
 
C# Code...
 
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
 
public class CustomScript : ScriptBase
{
    public override async Task<HttpResponseMessage> ExecuteAsync()
    {
        try
        {
            // Read the request body
            var requestBody = await this.Context.Request.Content.ReadAsStringAsync();
 
            // Parse the JSON content
            var json = JObject.Parse(requestBody);
            var name = json["Name"].ToString();
 
            // Create the greeting message
            var greeting = $"Hello, {name}";
 
            // Create the response
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent($"{{ \"Greeting\": \"{greeting}\" }}", Encoding.UTF8, "application/json")
            };
 
            return response;
        }
        catch (Exception ex)
        {
            // Log the exception and return an error response
            var errorResponse = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent($"{{ \"error\": \"{ex.Message}\" }}", Encoding.UTF8, "application/json")
            };
 
            return errorResponse;
        }
    }
}
 
 
 
 
Thank you for any help!
Categories:

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November 2024 Newsletter…

November 2024 Community Newsletter…

Community Update Oct 28…

Power Platform Community Update…

Tuesday Tip #9 Get Recognized…

Welcome to a brand new series, Tuesday Tips…

Leaderboard

#1
WarrenBelz Profile Picture

WarrenBelz 144,316

#2
RandyHayes Profile Picture

RandyHayes 76,308

#3
Pstork1 Profile Picture

Pstork1 64,290

Leaderboard

Featured topics

Loading started
Loading complete