Wrong Content-Type in response in IErrorHandler - rest

I would like to send response to my service in JSON format. I catch my custom errors in my custom behavior:
void IErrorHandler.ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
XDocument errorMsg = XDocument.Parse("<errorMessage>" + error.Message + "</errorMessage>");
var jsonWriter = new JsonErrorBodyWriter(errorMsg);
fault = Message.CreateMessage(version, null, jsonWriter);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
prop.StatusCode = HttpStatusCode.Unauthorized;
prop.Headers.Add("Content-Type", "application/json; charset=utf-8");
prop.Headers[HttpRequestHeader.ContentType] = "application/json; charset=utf-8";
--Tried different ways to achieve this
fault.Properties.Add(HttpResponseMessageProperty.Name, prop);
}
But I get wrong content-type in response. And also I couldn't manage to write any custom header like :
prop.Headers.Add("Test", "Value");
Reponse:
HTTP/1.1 401 Unauthorized
Content-Type: application/xml; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Wed, 30 Sep 2020 08:41:15 GMT
Content-Length: 37
{"description":"Autorization Failed"}
What is wrong in my code?

Related

Downloading data from REST API response but getting a response code of -1

REST API details from documentation:
GET /REST/sql_snapshot/2003-03-01.sql.gz HTTP/1.1
Host: some.api.net
Authorization: Basic qpow3i12o3
The response shown below omits the message body, which contains binary compressed SQL data.
HTTP/1.1 200 OK
Date: Wed, 05 Mar 2003 10:19:46 GMT
Server: Apache/1.3.22 (Unix) (Red-Hat/Linux)Content-Type: application/octet-stream
I'm getting a response code of -1 from below.
URL url = new URL("https://some.api.net/REST/sql_snapshot/2003-03-01.sql.gz");
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/octet-stream");
connection.setDoOutput(true);
connection.connect();

How to get last-modified from http header with dartio HttpClient

Hi there I want get Last_modified from http header with dart.io HttpClient()
code sample is:
var client = new HttpClient();
HttpClientRequest req = await client.getUrl(Uri.parse("sayagh.asnafhormozgan.ir/wp-content/tables/essentials.csv"));
var a = req.headers.value("lastModifiedHeader");
but a returns null;
how I can get Last modified?
but when I get it with curl:
curl -v "sayagh.asnafhormozgan.ir/wp-content/tables/drawer.csv"
* Trying 51.89.173.235:80...
* TCP_NODELAY set
* Connected to sayagh.asnafhormozgan.ir (51.89.173.235) port 80 (#0)
> GET /wp-content/tables/drawer.csv HTTP/1.1
> Host: sayagh.asnafhormozgan.ir
> User-Agent: curl/7.65.3
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Server: nginx
< Date: Thu, 19 Sep 2019 10:05:37 GMT
< Content-Type: text/csv
< Content-Length: 599
< Connection: keep-alive
< Last-Modified: Thu, 19 Sep 2019 09:38:30 GMT
< Accept-Ranges: bytes
< Cache-Control: max-age=0
< Expires: Thu, 19 Sep 2019 10:05:37 GMT
<
You'll need to wait for the second future to get the response, i.e.:
A getUrl request is a two-step process, triggered by two Futures. When
the first future completes with a HttpClientRequest, the underlying
network connection has been established, but no data has been sent. In
the callback function for the first future, the HTTP headers and body
can be set on the request. Either the first write to the request
object or a call to close sends the request to the server.
See https://api.dartlang.org/stable/2.5.0/dart-io/HttpClient-class.html
Also it should be 'last-modified' and not 'lastModifiedHeader' (or even better use the static const variable HttpHeaders.lastModifiedHeader), e.g.:
HttpClient client = HttpClient();
HttpClientRequest req = await client.getUrl(Uri.parse(
'http://sayagh.asnafhormozgan.ir/wp-content/tables/essentials.csv'));
HttpClientResponse response = await req.close();
print(response.headers.value(HttpHeaders.lastModifiedHeader));

HTTP OPTIONS in Xamarin Forms

Getting "204 Status Code" as No Content
Here is a simple example of OPTIONS request:
var httpClient = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Options, new Uri("http://myapi.com"));
var response = await httpClient.SendAsync(request);
Just wondering why should you need to make one? OPTIONS is used to identify allowed request methods:
To find out which request methods a server supports, one can use curl
and issue an OPTIONS request:
curl -X OPTIONS http://example.org -i
The response then contains an Allow header with the allowed methods:
HTTP/1.1 200 OK
Allow: OPTIONS, GET, HEAD, POST
Cache-Control: max-age=604800
Date: Thu, 13 Oct 2016 11:45:00 GMT
Expires: Thu, 20 Oct 2016 11:45:00 GMT
Server: EOS (lax004/2813)
x-ec-custom-error: 1
Content-Length: 0
Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS

Angular2 Http Response missing header key/values

I'm making an http.patch call to a REST API that is successful (Status 200) but not all the response headers key/values are being returned. I'm interested in the ETag key/value.
Here is a code snippet:
let etag:number = 0;
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('If-Match', String(etag));
this.http.patch(
'http://example.com:9002/api/myresource/',
JSON.stringify(dto),
{headers: headers}
)
.subscribe(
(response:Response) => {
let headers:Headers = response.headers;
let etag:String = headers.get('ETag');
console.log(etag);
}
);
When making the same call with a REST Client (Postman), the response header contains:
Content-Type: application/hal+json;charset=UTF-8
Date: Mon, 01 Feb 2016 05:21:09 GMT
ETag: "1"
Last-Modified: Mon, 01 Feb 2016 05:15:32 GMT
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
X-Application-Context: application:dev:9002
Is the missing response header key/values a bug?
Can the issue be resolved with configuration?
This isn't an Angular issue, rather a CORS one. By definition, CORS will only return six "simple" headers: Cache-Control, Content-Language, Content-Type, Expires, Last-Modified and Pragma.
That's why you see the full set when using a REST client such as Postman, yet when calling from your Angular client, you'll only see the set limited by CORS.
To solve this, you'll need to add an Access-Control-Expose-Headers header along the following lines:
let headers = new Headers();
headers.append('Access-Control-Expose-Headers', 'etag');
let options = new RequestOptions({ headers: headers });
return this.http.get(uri, options).map(this.extractData).catch(this.catchError);
Note that you may need to augment the server side code to support the required exposed headers.
In my case (C#), I revised the EnableCors call (within WebApiConfig) to include "ETAG" in the list of exposed headers (the fourth parameter of the EnableCorsAttribute function).

LWP::UserAgent returns incomplete 2GB response message

I am using LWP::UserAgentto send request on a URL. But sometime in the response I am getting incomplete XML response.
Code
$args->{pua} = LWP::UserAgent->new();
$args->{header} = HTTP::Headers->new;
$args->{header}->header("Content-Type" => "text/xml", "SOAPAction" => $args->{soapaction});
$request = HTTP::Request->new( "POST", $args->{endpoint}, $args->{header}, $args->{xml});
$response = $args->{pua}->simple_request($request);
my $xmlResponse = $response->content;
In the $xmlResponse sometime I am getting incomplete response. Why is it happening?
ResponseHeader
Connection: close
Date: Tue, 19 May 2015 11:07:37 GMT
Server: nginx/1.6.2
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Type: text/xml;charset=ISO-8859-1
Client-Date: Tue, 19 May 2015 11:07:40 GMT
Client-Peer: 202.77.98.11:80
Client-Response-Num: 1
Client-Transfer-Encoding: chunked
X-Frame-Options: SAMEORIGIN
LWP may return incomplete response when it failed to read whole body because of the timeout or other read error. In this case $response->is_success will be true and $response->code will be 200, but response headers will contain special header called X-Died.
So you can check this header:
unless ($response->is_success) {
die "Response failed: ", $response->status_line;
}
if ($response->header('X-Died')) {
die "Response failed (internal): ", $response->header('X-Died');
}