I wanted to host a API in WPF. I have tried implementing Self hosted api using below article.
When i have done the implementation for Console application. I was able to verify with PostMan tool to verify get API and it works fine.
But if i implement the same in WPF like below:
MainWindow() in WPF:
string baseAddress = "http://localhost:4444/";
public MainWindow()
{
InitializeComponent();
WebApp.Start<StartUp>(baseAddress);
GetCall();
}
StartUp class:
using Owin;
using System.Web.Http;
namespace WpfApp3
{
public class StartUp
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
appBuilder.UseWebApi(config);
Owin.CorsExtensions.UseCors(appBuilder,
Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
}
}
GET API implementation like below.
string baseAddress = "http://localhost:4444/";
HttpClient client = new HttpClient();
var res = await client.GetStringAsync(baseAddress "api/demo");
After Get API called: I got below exception.
Exception :System.Threading.Tasks.TaskCanceledException: 'The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.'
Four Inner Exceptions:
- TimeoutException: The operation was canceled.
- TaskCanceledException: The operation was canceled.
- IOException: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request..
- SocketException: The I/O operation has been aborted because of either a thread exit or an application request.
So, I am struggling to find a solution for this. Please provide a solution on this. am i going in the right way or not.
Or Is there any other solution for WPF to host api which will help a lot.
CodePudding user response:
Do you have a DemoController
? If you copied the ValuesController
class from the example, the URI should be "api/values" and nothing else:
string baseAddress = "http://localhost:4444/";
HttpClient client = new HttpClient();
var res = await client.GetStringAsync(baseAddress "api/values");
CodePudding user response:
I got a solution from this article.
https://blog.codeinside.eu/2015/09/29/wpf-chrome-embedded-and-webapi-selfhosting/
Now i am able to host api in WPF.