client.DeleteAsync - include object in body - asp.net-web-api

I have an ASP.NET MVC 5 website - in C# client code I am using HttpClient.PutAsJsonAsync(path, myObject) fine to call a Json API (the API is also mine created in Web API).
client.BaseAddress = new Uri("http://mydomain");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PutAsJsonAsync("api/something", myObj);
I would like to do the same with a Delete verb. However client.DeleteAsync does not allow an object to be passed in the body. (I would like to record the reason for deletion alongside the Id of the item to delete in the URI).
Is there a way to do this?

You'll have to give up a little in terms of convenience since the higher-level DeleteAsync doesn't support a body, but it's still pretty straightforward to do it the "long way":
var request = new HttpRequestMessage {
Method = HttpMethod.Delete,
RequestUri = new Uri("http://mydomain/api/something"),
Content = new StringContent(JsonConvert.SerializeObject(myObj), Encoding.UTF8, "application/json")
};
var response = await client.SendAsync(request);

Related

Attaching zip file is not working in WEB API, but works via POSTMAN

I have an .net core WEB API method that needs to call another external API (java) which expects .zip file. When try to access the external API via Postman by attaching the file, it is working fine (getting expected response). However when i pass the same parameters via my WEB API code, it is throwing 403-Forbidden error.
Please let me know if i am missing anything....
Thanks in advance!!!
request-header
request-body-file-attached
response-403-error
API code: for connecting to api:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("pane", "forward");
parameters.Add("forward_path", "/store/execute");
parameters.Add("csrf", "1996fe6b2d0c97a8a0db725a10432d83");
parameters.Add("data_format", "binary");
newContent = new FormUrlEncodedContent(parameters);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent con;// = new StringContent("file_name");
//form.Add(con, "file_name");
form.Add(newContent);
var str = new FileStream("D:\\dummy\\xmlstore.zip", FileMode.Open);
con = new StreamContent(str);
con.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file_name",
FileName = "xmlstore.zip"
};
con.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
form.Add(con);
client.DefaultRequestHeaders.Add("Cookie", "JSESSIONID=05DEB277E294CBF73288F2E24682C7EE;");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate"));
client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("br"));
client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("user-agent", "1"));
var resp = client.PostAsync("java-api", con).Result;

Can a REST API be used within a Web API service?

I need to create a Web API "wrapper" that is consumed by a client, but in this Web API Service, I actually need to create a POST request to a different REST API service that is running on the same IIS server that does some work and returns StringContent that I pass back to the client via a JSON HttpResponse. Is this possible? Instead of the client making direct calls to the actual REST API and returning data they don't need/want, they would call my Web API service and I would only return them the required data. I know this was done in the old SOAP WSDL model.
If I need the client to pass in a couple parameters that are required for my POST request, would I be having the client use a GET or POST request?
This is an sample code i used call API inside another API using POST method.
using (var client = new HttpClient())
{
string query;
using (var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
{"username", username},
{"password", password}
}))
{
query = content.ReadAsStringAsync().Result;
}
var model = new{
username = txtUsername.Text,
password = txtPassword.Text
};
var json = JsonConvert.SerializeObject(model);
var user = new StringContent(json, Encoding.UTF8, "application/json");
using (var response = await client.PostAsync(#"http://localhost/dataagent/api/user/authenticate", user))
{
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
// handle result here
}
}
}

Globally formatting .net Web Api response

I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.
Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.
public IHttpActionResult GetServices()
{
var data = _dataService.Get(); //retrieves data from a service
var result = JsonConvert.DeserializeObject(data); //convert to object
return Ok(result);
}
What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.
On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.
HttpConfiguration configuration = new HttpConfiguration();
var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new DefaultContractResolver();
Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?
Thanks
If you want to just pass through the json (Option A), you can do this
public IHttpActionResult GetServices() {
var json = _dataService.Get(); //retrieves data from a service
HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = content;
return ResponseMessage(response);
}

Payments Api Doesn't Return Link in Headers via C#

I'm calling the Square Connect payments API using C#. The documentation says I should get a header key of "link" if results are paged. However, I only ever get 100 results in the response and there isn't a header key of "link". Here's my code:
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", String.Format("Bearer {0}", "<Token>"));
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
DateTime startDate = DateTime.UtcNow.Date;
var paymentUrl = string.Format("https://connect.squareup.com/v1/me/payments?begin_time={0:yyyy-MM-dd}T00:00:00Z&end_time={1:yyyy-MM-dd}T00:00:00Z", startDate.AddDays(-25).Date, startDate.Date);
var responseMessage = await client.GetAsync(paymentUrl);
You should only use the location_id urls to retrieve your payment history with the v1 APIs. Alternatively you can use the v2 Transaction APIs to more effectively retrieve your payment info.

Do Get request with a complex type parameter in the request body with web api

I want to do an integration test for the below action.
How can I pass my requestDto object in the integration test?
Neither the GetAsync nor SendAsync method has an overload parameter to pass a custom object to the server.
[Route("{startDate:datetime}")]
[HttpGet]
public HttpResponseMessage Get(DateTime startDate, [FromBody]LessonplannerGetRequest request)
{
request.StartDate = startDate;
var lessonplannerResponse = _service.GetPeriodsByWeekStartDate(request);
return Request.CreateResponse<LessonplannerResponse>(HttpStatusCode.OK, lessonplannerResponse);
}
[Test]
public void Get_Lessons_By_Date()
{
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, _server.BaseAddress + "/api/lessonplanner/2014-01-14");
var myRequestDto = new LessonplannerGetRequest();
// Act => QUESTION: HOW do I pass the myRequestDto ???
var response = _client.SendAsync(request, new CancellationToken()).Result;
// Assert
Assert.That(response.StatusCode == HttpStatusCode.OK);
}
UPDATE
As Darrel Miller said:"Technically HTTP says you can send a body, it just says the body doesn't mean anything and cannot be used. HttpClient won't let you send one."
I post here my integration test with HttpClient doing a Get request with complex type + FromBody:
// Arrange
var request = new HttpRequestMessage(HttpMethod.Get, _server.BaseAddress + "/api/lessonplanner/2014-01-14");
var myRequestDto = new LessonplannerGetRequest{ FirstDayOfWeek = DayOfWeek.Sunday, SchoolyearId = 1, StartDate = DateTime.Today};
request.Content = new ObjectContent<LessonplannerGetRequest>(myRequestDto, new JsonMediaTypeFormatter());
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// Act
var response = _client.SendAsync(request, new CancellationToken()).Result;
// Assert
Assert.That(response.StatusCode == HttpStatusCode.OK);
Of course is this is not the Http way some might consider doing it differentlly sending complex type via FromUri/query string.
HTML specifications says you cannot send a GET with a body.
HTTP specs allows it.
WebAPI allows it, because it is a service/REST and implements HTTP but not HTML, but many clients and browser won't allow it because they implement both specs and try to be strict.
As for the specifications (RFC1866, page 46; HTML 4.x section 17.13.3) itself, it states:
If the method is "get" and the action is an HTTP URI, the user agent takes the value of action, appends a `?' to it, then appends the form data set, encoded using the "application/x-www-form-urlencoded" content type.
(e.g. if you do a <form> with GET, it will parse all the form params and set them in the query string ?a=b).
In term of pure HTTP and in the context of REST services, nothing prevents that behavior, but not all clients will be able to handle it. It's mostly a best-practice advise when it comes to REST/WebAPI to not handle body data from HttpGet, only URI data (the opposite, POST /action?filter=all is usually tolerated for metadata/action qualifiers, but that's another discussion).
So yeah, it's at your own risk, even if used only internally. As not all clients handle it (e.g. HttpRequestMessage), so you might run into trouble like you have.
You should NOT pass a GET body with HTTPClient.

Resources