HttpClient DeleteAsync with Multiple records - c#

I'm using the sendgrid api here:
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#Delete-a-Recipient-DELETE
and it shows passing an array of strings to the DELETE call. When I look at the signature of System.Net.Http.HttpClient, DELETE does not allow for content to be passed in.
Is there a standard around DELETE that does not allow for multiple content passed at the same time?
API definition:

The HTTP/1.1 RFC states that a DELETE request's payload has no defined semantics.
It's not illegal to include a payload, but this means that if a payload is included, it should be ignored.
Many HTTP clients, such as the one provided by the .NET framework, don't provide an interface to include a payload when it has no defined semantics for the method.
Unfortunately, many REST APIs do require a payload with these methods. You can accomplish this by manually creating a HttpRequestMessage object, setting the Method and Content properties, and passing it to the HTTP client's SendAsync method.

Create an extension method
public static class HttpClientExtensions
{
public static Task<HttpResponseMessage> Delete(this HttpClient client, HttpContent content)
{
var request = new HttpRequestMessage { Method = "DELETE", Content = content);
return client.SendAsync(request);
}
}
However I cannot recommend it, as it breaks basic assumptions of HTTP, which allows efficient HTTP Proxies to work.
The "correct method" around this problem is to use HTTP 2.0 (or HTTP 1.1 Pipelining, which is deprecated due to it being mostly broken, but you could try it out) to create multiple DELETE requests. In theory that solution does not require any code change.

Related

Can you use custom HTTP request methods with http.client?

Is there a way to use HTTP request methods that are not implemented by System.Net.Http.HttpMethod?
I try to update files with a REST interface. The way it is implemented, I GET a list of files and their hashes. Then I check if any of these files have changed on my side and if so, I POST each file to the API, otherwise I skip it.
When I'm done, the endpoint expects an UPDATE request to know that I'm done sending files. But there is no UPDATE method in HttpMethod.
Is there a way to alter REQUEST_METHOD manually in a HttpRequestMessage or do they need to recode the endpoint?
Looking up System.Net.Http.HttpMethod only gives the following options: GET, PUT, POST, DELETE, HEAD, OPTIONS, TRACE, PATCH and CONNECT. There is no obvious way to add a custom method.
In the case where you need an HttpMethod that does not exist in the static properties of the class, you can just use the constructor which allows you to pass any string method:
var customHttpMethod = new HttpMethod("UPDATE");

Using Digest Authentication with Shelly Power Product, cannot get 200 code from second GET requests

I'm working on getting some Shelly Power products (API Documents Here) able to be called from a .NET 6 Minimal API application.
Following the Digest Authentication documentation from Shelly and the RFC 7616, I have an extension method for the HttpClient that basically takes an HttpRequestMessage for the URL http:///rpc/Switch.GetStatus?id=0. After setting the normal headers (Accept, User-Agent, etc.) for that HttpRequestMessage, it passes that HttpRequestMessage as a parameter to that extension method.
After passing the HttpRequestMessage to the extension method, it is cloned into a new HttpRequestMessage, with the content, version, and headers. After that, the first SendAync() call is made, and the 401 response is generated containing the WWW-Authentication header. After parsing out the realm, nonce, and qop, the rounds of hashing is done according to the specs. Shelly uses SHA256 instead of MD5 (as they should) but overall follows the standard for hashing. After this, the newly formed Authentication Header string is created and it is formatted as such:
Digest username="admin", realm="shellyplugus-083af2018b68", nonce="633e7ba8", cnonce=8724224, response="9B15CEBA6E5FD862271954AC2C40948D6237511B83748143FF763A0E76B1A346", algorithm=SHA-256
The following code is the creation of an AuthHeaderObject, the creation of the string above, and gets added to the cloned HttpRequestMessage (called "digestRequest" here):
var digestAuthHeaders = new DigestAuthHeader(
"Digest", realm, username, password, nonce, qop, clientNonce, "SHA-256");
var digestRequestHeader = digestAuthHeaders.DigestRequestHeader();
digestRequest.Headers.Add("Authorization", digestRequestHeader);
The 2nd SendAsync() passing the cloned request and completion option enum.
var authRes = await client.SendAsync(digestRequest, httpCompletionOption);
The issue after this is that I am still getting a 401 response. Not even getting another code indicating another issue. It is just acting like the same request has been made.
Should I forgo the cloning of the HttpRequestMessage and simply create a new one? Does anything immediately standout that is incorrect? I want to note that Shelly only specifies that Authorization string only contain the values included, it does not require uri, qop, opaque, and some of the others.
Looks like there is a direct way to do this by using HttpClientHanlder and setting the NetworkCredentials property, then passing the Handler to the HttpClient.

C# http request add json object in the content

I'm making an http request post to an external api. I am constructing a json object to add to the request body. How can I check if the added body/content is correct before it is sent.
public async void TestAuthentication()
{
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://test"),
Method = HttpMethod.Post
};
var jsonObj = new
{
data = "eneAZDnJP/5B6r/X6RyAlP3J",
};
request.Content = new StringContent(JsonConvert.SerializeObject(jsonObj), Encoding.UTF8, "application/json");
var response = await client.SendAsync(request);
}
If you are not sure whether the serialization works as intended, you could give it a shot in LINQpad or dotnetfiddle.net. See my example that returns the JSON on the console. These tools are great for quick prototyping a method or a snippet, if you are not sure if a piece of code works as intended.
You could also check in Wireshark, but that could be a bit of an overkill and works best if your connection if not encrypted (no HTTPS).
I personally tend to test code that calls some API the following way:
Make the called URL parameterizable (via the classes constructor)
If there is any variable data this data should be passed as the methods parameter(s)
For your test start an HTTP server from your test fixture (read on testing with xUnit or NUnit if you don't know what this means)
I use PeanutButter.SimpleHTTPServer for that
Pass the local IP to the class that accesses the API
Check whether the HTTP server received the expected data
Whether or not this kind of code shall be tested (this way) may be debatable, but I found this way to work kind of good. I used to abstract the HttpClient class away, but IMHO I would not recommend this anymore, because if the class accesses the API (and does not do anything else, which is important), the HTTP access is the crucial part that shall be tested and not mocked.

.NET 4.6 HttpResponse.PushPromise methods to manage http/2 PUSH_PROMISE header

I am a bit confused about PUSH PROMISE http/2 header handling in .NET4.6.
When I look HttpResponse.PushPromise there are two overloads:
One that accepts path to resource public void PushPromise(string path) - am assuming resource is then read and binary sent across to client.
Second public void PushPromise(string path, string method, NameValueCollection headers) that accepts sting method and NameValueCollection headers which I am failing to understand.
Why would I want to pass method (assuming HttpMethod like GET, POST, etc) and collection of headers inside PUSH PROMISE header?
From reading the HTTP/2 spec (Section 8.2), here is what I gather:
Passing the method
PUSH_PROMISE frames are required to be cacheable and safe. You have the option of using GET and HEAD, as those are the only two http methods that are defined as both safe and cacheable.
Passing headers
Since PUSH_PROMISE frames are required to be cacheable, this could be used to add specific Cache-Control directives to the promise. Section 8.2.2 of the spec states that a client has the option to download the promised stream and can refuse it, which I imagine a client would do if it found that it had an up-to-date version of the resource in its cache.
Controlling caching is the most obvious reason I can see for why you might pass headers, but there may be other reasons as well. If you're writing a custom client, you may use certain X-Headers to provide other hints (that aren't related to caching) to the client so it can decide whether or not it wants to accept the promised stream.
You'll want to pass headers for anything that will cause your response to vary (i.e. anything in your Vary response header). The biggest one I've found is compression.
Read those headers from the original client request and include them with your push promise, e.g.:
var headers = new NameValueCollection { { "accept-encoding", this.Request.Headers["accept-encoding"] } };
this.Response.PushPromise("~/Scripts/jquery.js", "GET", headers);`

Utilizing Web API on client side

I have created a simple web api controller in mvc4 containing 4 methods (one for each CRUD operation). I'm able to use fiddler to test that the methods in my controller work.
I'm now trying to make a unit test to prove that these work. I've managed to serialize my client side object into json format, but now how do I use this string of json to actually invoke my methods?
If it helps, I am using Json.NET to serialize my client object - although I don't think this extention actually handles the delivery and retreival of it to the server.
Your unit tests should be written against the controller - so you don't need to make an actual HTTP request to unit test your Web API code, you just call the methods.
From a design perspective, if you want a restful Web API, the client should be able to send a standard HTTP message without having to serialize the request.
This is the kind of approach I have used to post an object to a restful Web API:
HttpResponseMessage response;
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://url_to_service");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var responseTask = client.PostAsJsonAsync("api/resource/somethingelse", someObjectToPost).Result;
responseTask.Wait();
response = responseTask.Result;
if (response.IsSuccessStatusCode)
{
var contentTask = response.Content.ReadAsAsync<SomeResponseType>();
contentTask.Wait();
SomeResponseType responseContent = contentTask.Result;
}
else
{
//Handle error.
}
In this case, someObjectToPost is your client-side object, though you can leave it to Web API to serialize it for you. In the above example I am assuming the reponse is of fictional type SomeResponseType - you can also use ReadAsStringAsync if the response is expected to be plain text.
The code presented here by nick_w is correct. You need to use HttpClient object. And as Steve Fenton mentioned, to create unit test you don't want to do it - rather test directly against controller. But for the functional test you can do it. I've done same thing. I've created helper class so I need only to call one of Http helper methods, depending if it is GET or POST, etc. that I do. This helper uses generic types so it operates with any types that being passed.

Categories