Kishan Vaishnav
Kishan Vaishnav

Reputation: 2631

Calling internal (Endpoint) function in WebAPI

I am using Hangfire to execute recurring jobs in my web API and I use System.Web.HttpContext.Current.Server.MapPath in the "RoutineMethod" function.

But the problem is it throws object null exception. I searched the problem and found that recurring jobs don't use http threads, they use background threads.

Now to resolve this problem I need to call my internal (endpoint) using httpclient.

But to do that I need to give URL of the Web API (to generate URI). So is there any other way to call internal function using httpclient.

My current code:

public static async Task<IHttpActionResult> RoutineTask()
        {
            //It was like this before.
            //await new DemoController().RoutineMethod();
            //await new DemoController().RoutineMethod2();

            //I am planning to do this.
            using (var client = new HttpClient())
            {
                //But I need to give URI which I don't think is a good idea.
                var uri = new Uri("http://localhost/DemoApp/api/DemoController/RoutineMethod");
                await client.GetAsync(uri);

            }

            return new DemoController().Ok();
        }

Upvotes: 0

Views: 2321

Answers (1)

Maess
Maess

Reputation: 4156

The short answer is no. The HttpClient, as its name implies, requires an http connection.

There are no smell issues with storing service connection information in a configuration file.

However, to expand on Nkosi's comment, it appears that since your code can create an instance of DemoController, that it must have a reference to that controller's project or even be in the same project. I would extract the interesting code into a library or service that all areas needing the information can reference.

Upvotes: 1

Related Questions