HTTP POST not working in OWIN Self-Host Web API - c#

I am self self hosting a Web API. Any Get Reqeust I make from my integration tests works fine. However any POST request throws connection refused. I can't seem to get a handle on what is happening.
Error Message
system.Net.HttpRequestException: An error occured while sending the request to the remote server. SocketException: no connection could be made because the target machine actively refused.
Code
using (WebApp.Start<App_Start.TestConfiguration>("http:/localhost:8216"))
{
var client = new HttpClient();
client.BaseAddress = new System.Uri("http://127.0.0.1:8216");
var response = await client.PostAsync("/api/MyController", new StringContent("something"));
}
controller
public string Post(string value)
{
return "Hello!";
}

I've got the same issue and found that it is necessary to use [FromBody] attribute before your method params. In this case it can parse request payload and you can reach your methods
Hope that helps

Could it be you're missing a / on:
using (WebApp.Start<App_Start.TestConfiguration>("http:/localhost:8216"))
it should be http://localhost:8216.

Related

call a WebAPI from Windows Service

I have errors after call webapi from Windows Service
first error is :
An error occurred while sending the request.
second error is :
The underlying connection was closed: Could not establish trust
relationship for the SSL/TLS secure channel.
You could use System.Net.Http.HttpClient.. You will obviously need to edit the fake base address and request URI in the example below but this also shows a basic way to check the response status as well.
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:8888/");
//Usage
HttpResponseMessage response = client.GetAsync("api/importresults/1").Result;
if (response.IsSuccessStatusCode){var dto = response.Content.ReadAsAsync<ImportResultDTO>().Result;}
else{Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);}

Adding SSL cert causes 404 only in browser calls

I am working in an internal corporate environment. We have created a webapi installed on iis on port 85. We call this from another MVC HelperApp on port 86. It all works as expected. Now we want to tighten security and add an SSL cert to iis on port 444 and bind it to our API.
Initially we test it with Postman, SoapUI, and a C# console app and it all works. Now we try calling it from our MVC HelperApp and it returns a 404 sometimes.
Deeper debugging; I put the code into a C# DLL (see below). Using the console app I call the Dll.PostAPI and it works as expected. Now I call that same Dll.PostAPI from the MVC HelperApp and it won't work. When I step through the code I make it as far as this line await client.PostAsync(url, data); and the code bizarrely ends, it doesn't return and it doesn't throw an exception. Same for Post and Get. I figure it makes the call and nothing is returned, no response and no error.
Also, if I change the url to "https://httpbin.org/post" or to the open http port85 on iss it will work. I have concluded that the C# code is not the problem (but I'm open to being wrong).
Therefore I have come to the conclusion that for some reason the port or cert is refusing calls from browsers.
We are looking at:
the "Subject Alternative Name" but all the examples show
WWW.Addresses which we are not using.
the "Friendly Name" on the cert creation.
and CORS Cross-Origin Resource Sharing.
These are all subjects we lack knowledge in.
This is the calling code used exactly the same in the console app and the web app:
var lib = new HttpsLibrary.ApiCaller();
lib.makeHttpsCall();
This is what's in the DLL that gets called:
public async Task<string> makeHttpsCall()
{
try
{
List<Quote> quotes = new List<Quote>();
quotes.Add(CreateDummyQuote());
var json = JsonConvert.SerializeObject(quotes);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://httpbin.org/post"; //this works in Browser
//url = "https://thepath:444//api/ProcessQuotes"; //444 DOES NOT WORK in browsers only. OK in console app.
//url = "http://thepath:85/api/ProcessQuotes"; //85 works.
var client = new HttpClient();
var response = await client.PostAsync(url, data); //<<<this line never returns when called from browser.
//var response = await client.GetAsync(url); //same outcome for Get or Post
var result = await response.Content.ReadAsStringAsync();
return result;
}
catch (Exception ex)
{
throw;
}
}

SSL TLS communication in c# with self signed certificate not working

I have a .pem certificate file which is used to communicate between two servers. For communication I have written a program in C# like this:
var client = new RestClient("https://aaaaa.com:1111");
client.ClientCertificates = new X509CertificateCollection();
client.ClientCertificates.Add(new X509Certificate(#"C:\Users\aaa\Desktop\bbb.pem"));
var request = new RestRequest("/qqq/www", Method.POST);
request.AddJsonBody(new { create = new { msgBdy="Test" } });
var response = client.Execute(request);
Console.WriteLine(response.StatusCode);
//The underlying connection was closed: An unexpected error occurred on a send.
When I post the request through SoapUI it goes through, but when I try to send it through Postman or the above C# program it doesn't.
Screenshot from wireshark is below:
The change cipher spec event is called for the successful API call but through postman and c# application this event is never called.
I have tried to do this as explained in this article as well https://www.codeproject.com/Articles/326574/An-Introduction-to-Mutual-SSL-Authentication but that also didn't work.
How can I fix this issue.

How to inject Http Parser into OWIN Self host server

I have http clients that are sending "POST" requests with no contents which cause the selfhost server to throw http 411 error , the http clients are for customers that it is not a solution to modify them , so the only way to modify my server to not throw this error when "POST" request arrive without content .
it seem it is happening in the low level , no attribute or filter or even app.Use worked to catch the request before the error get thrown
it mostly happening at the next level when TCP content get converted to HTTP request.
So basically I am looking for the point when before the server parse the TCP contents into HTTP request
static void Main(string[] args)
{
var baseAddress = new Uri("http://localhost:8073");
var config = new HttpSelfHostConfiguration(baseAddress);
config.Routes.MapHttpRoute("default", "{controller}");
using (var svr = new HttpSelfHostServer(config))
{
svr.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
It turned out the HTTP parser is not inject-able, it is kind of limitation in my openion to any http server , as the trip of data from TCP client until it get converted to HTTP request is black boxed at least in OWIN self host server

HttpClient GET request fails, POST Succeeds

In a Xamarin application (backed by ASP.NET WebApi), I'm having trouble getting [all of] my GET requests to succeed -- they return 404. In fact, when watching network traffic in Fiddler, I don't even see the request happen.
Here is [basically] what I'm doing:
public async Task<bool> ValidateSponsor(string attendeeId, string sponsorId)
{
string address = String.Format("{0}/Sponsors/?attendeeId={1}&sponsorId={2}", BASE_URI, attendeeId, sponsorId);
var response = await client.GetAsync(address);
var content = response.content;
if (!response.IsSuccessStatusCode)
throw new HttpRequestException("Check your network connection and try again.");
string result = await content.ReadAsStringAsync();
return Convert.ToBoolean(result);
}
If I copy out the address variable and paste it into a browser, it succeeds. POST requests (to different methods, of course) succeed. I've also tried using the PCL version RestSharp but get the same results -- POST succeeds and GET fails.
Edit:
This looks like it also may only be a problem when deployed to Azure, it works fine locally.

Categories