WebApi: */* media type handling - asp.net-web-api

In my application I'm making some javascript requests to my Api Controllers to get some html formatted strings. When those requests are made with Accept: */* HTTP header (jQuery $.get method), so by default JsonMediaTypeFormatter is used and the data is returned with Content-Type: application/json in JSON format.
What I would like is to handle */* requests as text/html. So I tried to create a custom MediaTypeFormatter that supports */* media type, but it gives me the following error
The 'MediaTypeHeaderValue' of */* cannot be used as a supported
media type because it is a media range.`
Alternatively I could always provide correct expected data types in my requests, but I'm curious if there's a way to handle */* media types.

The above behavior is due to the following:
The default con-neg algorithm in Web API has the following precedence order of choosing the formatter for response:
Formatter match based on Media Type Mapping.
Formatter match based on Request Accept header's media type.
Formatter match based on Request Content-Type header's media type.
Formatter match based on if it can serialize the response data’s Type.
Now, JsonMediaTypeFormatter comes with a built-in media type mapping called XmlHttpRequestHeaderMapping which inspects an incoming request and sees if the request has the header x-requested-with: XMLHttpRequest and also if there is no accept header or if the Accept header is only having */*.
Since your request is mostly probably looking like below, according to the precedence order JsonMediaTypeFormatter is chosen as the one writing the response:
GET /api/something
Accept: */*
x-requested-with: XMLHttpRequest
A solution for your issue would be is to explicitly ask for "text/html" as this is what you are expecting.
GET /api/something
Accept: text/html
x-requested-with: XMLHttpRequest
Couple of very old blog posts about Content negotiation that I wrote:
http://blogs.msdn.com/b/kiranchalla/archive/2012/02/25/content-negotiation-in-asp-net-mvc4-web-api-beta-part-1.aspx
http://blogs.msdn.com/b/kiranchalla/archive/2012/02/27/content-negotiation-in-asp-net-mvc4-web-api-beta-part-2.aspx

Great question.
You can't set */* to be a supported media type, but what you can do is set your formatter to be the first one. Web API will pick the first formatter in the formatter collection that can write out the type if there is no Accept header or if the Accept header is */*.
So you'd want to configure your Web API like this:
config.Formatters.Insert(0, new MyHtmlFormatter());

Related

Getting Jmeter to generate the boundary dashes in the Content-Type header (eg boundary=--V0a4bfux...)

This what my HTTP request is generating
Content-Type: multipart/form-data; boundary=V0a4bfuxfGhaH_Voo_Gu6oAEtj5FJNcp; charset=UTF-8
However, when compared to the POST data, it is lacking the 2 dashes in the front, which causes the server to reject the request:
--V0a4bfuxfGhaH_Voo_Gu6oAEtj5FJNcp
Content-Disposition: form-data; data="dataToBeSent"
--V0a4bfuxfGhaH_Voo_Gu6oAEtj5FJNcp--
How do I get Jmeter to generate the dashes in the header?
(besides from manually creating the multipart form)
Note:
I am using the 'Use multipart/formdata for POST' option.
If I intercept the request and manually add the dashes in the header, the
server accepts the request.
You don't need to generate these values, the solution is to tick Use multipart/form-data for POST box in the HTTP Request sampler (or in the HTTP Request Defaults)
If you have any definition of Content-Type header in the HTTP Header Manager - you need to remove it and let JMeter generate appropriate Content-Type header on its own.
The header doesn't need the dashes. This is simply how multipart/form-data works. The body is built as follows:
--<boundary>
<headers>
<content>
--<boundary>
<headers>
<content>
--<boundary>--
The -- part indicates a new part starts. The body ends with ---- to indicate no new parts will follow.

What is the "accept" part for?

When connecting to a website using Net::HTTP you can parse the URL and output each of the URL headers by using #.each_header. I understand what the encoding and the user agent and such means, but not what the "accept"=>["*/*"] part is. Is this the accepted payload? Or is it something else?
require 'net/http'
uri = URI('http://www.bible-history.com/subcat.php?id=2')
http://www.bible-history.com/subcat.php?id=2>
http_request = Net::HTTP::Get.new(uri)
http_request.each_header { |header| puts header }
# => {"accept-encoding"=>["gzip;q=1.0,deflate;q=0.6,identity;q=0.3"], "accept"=>["*/*"], "user-agent"=>["Ruby"], "host"=>["www.bible-history.com"]}
From https://www.w3.org/Protocols/HTTP/HTRQ_Headers.html#z3
This field contains a semicolon-separated list of representation schemes ( Content-Type metainformation values) which will be accepted in the response to this request.
Basically, it specifies what kinds of content you can read back. If you write an api client, you may only be interested in application/json, for example (and you couldn't care less about text/html).
In this case, your header would look like this:
Accept: application/json
And the app will know not to send any html your way.
Using the Accept header, the client can specify MIME types they are willing to accept for the requested URL. If the requested resource is e.g. available in multiple representations (e.g an image as PNG, JPG or SVG), the user agent can specify that they want the PNG version only. It is up to the server to honor this request.
In your example, the request header specifies that you are willing to accept any content type.
The header is defined in RFC 2616.

JMeter Multipart JSON Request Form Data

I am trying to construct a HTTP Request through JMeter that uses a multipart data body.
I have a HTTP Header Manager that has COntent-Type set to multipart/form-data; boundary=AaB03x. I selected 'Use multipart/form-data for POST'.
I then have a data body created as,
`-----------------------------AaB03x
Content-Type: application/json
Content-Disposition: form-data; name="part1"
{"jsonKey1": "JsonValue1" }
-----------------------------AaB03x
Content-Type: application/json
Content-Disposition: form-data; name="part2"
{
"jsonKey2": "JsonValue2"
}
-----------------------------AaB03x
Content-Type: application/octet-stream
Content-Disposition: form-data; name="part3"
File Content here!!!!
-----------------------------AaB03x`
When I run this, I see that the request doesnt send the body correctly, instead it just sends some random data as,
POST data:
--vKOghkU7riRQbaANmmGpMs7j9TxCTUp3S2T0vE--
And gives an error response of,
`{"errorMsg":"Unable read headers from MultipartStream.","messageCode":"UnableReadHeadersFromMultipartStream","httpStat us":"BAD_REQUEST","requestName":"RequestName"}`
My second question is:
the part3 of the request sends a file to upload. Can I pass the file path somehow?
Given you set your own boundary and build your request manually I believe you need to uncheck Use multipart/form-data for POST in the HTTP Request Sampler
If your file encoding isn't very "exotic" you can try using __FileToString() function just instead of File Content here!!!!.
Looking into RFC 7578, it seems you also need a trailing -- at the end of the last line
You should try sending your JSON data as parameters. Also put your file path in the section for that... And even some servers don't actually need MIME type explicitly declared, you can check yours with some online tool like this one.
Your HTTP Request could look smethnig like:

Can I make my OData request in JSON format?

I know OData supports responding in JSON format when it's given the appropriate Accept header:
Accept: application/json
Some articles say you'll need to specify odata verbosity otherwise you'll get the default xml format, but I have not seen this to be actually true. But let me mention it anyway:
Accept: application/json;odata=verbose
But (how) can I make my request using JSON instead of a querystring?
OData doesn't provide a way to specify the query in a request body, it only supports the query in the URL. So the answer is that there's no way to do that in JSON. Note that it applies to GET requests. Modification requests (POST/PUT/...) do accept JSON as the payload (typically representing an entity for example), in which case simply specify the content type of the request in its Content-Type header.
There are java script libraries which let you build the query string using more structured code (as compared to just strings). For example the datajs http://datajs.codeplex.com/.

How to retrieve XML into Oracle PL/SQL via an HTTP Post transaction?

I'm trying to implement the "blog this" function from Flickr using the BloggerAPI to my pl/sql based CMS.
When Flickr sends me the posting transaction, the HTTP transaction looks like this:
POST /pls/website/!pkg.procAPI HTTP/1.1
Host: www.mydomain.com
Accept: */*
User-Agent: Flickr
Content-Type: text/xml; charset=utf-8
Content-Length: 1220
Expect: 100-continue
<?xml version="1.0" encoding="utf-8"?>
<methodCall>
<methodName>blogger.newPost</methodName>
<params>
<param><value><string>NO_APP_KEY</string></value></param>
<param><value><string>1</string></value></param>
<param><value><string>markj</string></value></param>
<param><value><string>markj</string></value></param>
<param><value><string>This is a test post from <a href="http://www.flickr.com/r/testpost"><img alt="flickr" src="http://www.flickr.com/images/flickr_logo_blog.gif" width="41" height="18" border="0" align="absmiddle" /></a>, a fancy photo sharing thing.</string></value></param>
<param><value><boolean>1</boolean></value></param>
</params>
</methodCall>
But my server is responding with an HTTP-400 Bad Request and the error message is "Signature Mismatch or Missing '='" and my pl/sql procedure never gets a chance to process the request. I suspect that the flexible parameter passing is getting hosed when looking at the message, but I don't know how else
The process to get the available blogs seems to work ok, but the content of the request doesn't have all the html entities as part of the message:
POST /pls/website/!pkg.procAPI HTTP/1.1
Host: www.mydomain.com
Accept: */*
User-Agent: Flickr
Content-Type: text/xml; charset=utf-8
Content-Length: 304
<?xml version="1.0" encoding="utf-8"?>
<methodCall>
<methodName>blogger.getUsersBlogs</methodName>
<params>
<param><value><string>NO-APP-KEY</string></value></param>
<param><value><string>mark</string></value></param>
<param><value><string>markj</string></value></param>
</params>
</methodCall>
Is there a way to get the xml data from the body of the http request directly? or some other approach I'm over looking?
Thanks,
Mark.
I opened a service request with Oracle and they confirmed that mod_plsql does not support retrieving httpheader variables. Here is the discussion I had on the SR:
ISSUE ANALYSIS
I need to confirm it, but Mark conclusion so far looks right to me,i.e. MOD_PLSQL is always invoking and processing PLSQL procedures and there is no way to read the raw HTTP request because MOD_PLSQL parses the request and checks if there is a PLSQL procedure with this name and if there are arguments to pass. If there are no arguments to pass but we are providing something else like the XML document, MODPLSQL gets puzzled and thinks this is a new pair of parameter and value when this is not really the case.
ANSWER
No, it is not possible to do it because MOD_PLSQL just treats requests with parameters which can be parsed and translated as a PLSQL procedure call with several arguments. MOD_PLSQL has no concept of a "httprequest" variable containing the whole request in the same way java has the HTTPRequest object
ISSUE ANALYSIS
Got the confirmation unless we pass it as a parameter we can not read it from MOD_PLSQL. In other words, if we pass the XML page in the HTTP request body we need to use something like java where we can treat the request in raw mode and we can read any HTTP header and the http body without restrictions of any kind.
Can the xml be sent as a file attachment? In other words change:
Content-Type: text/xml; charset=utf-8
to
Content-Type: multipart/form-data, boundary=AaB03x
Then add this before the xml:
--AaB03x
content-disposition: form-data; name="xmlfile"; filename="myfile.xml"
Content-Type: text/xml
And this after the xml:
--AaB03x--
Now, you set up the procedure for a file upload, as explained in this article:
Files, Uploads, and Downloads with Web PLSQL
Use UTL_HTTP
You can use the UTL_HTTP package to do this.
UTL_HTTP.read_text(
r IN OUT NOCOPY resp,
data OUT NOCOPY VARCHAR2,
len IN PLS_INTEGER DEFAULT NULL);
"The UTL_HTTP package supports HTTP 1.1 chunked transfer-encoding. When the response body is returned in chunked transfer-encoding format as indicated in the response header, the package automatically decodes the chunks and returns the response body in de-chunked format."
http://download.oracle.com/docs/cd/B10500_01/appdev.920/a96612/u_http.htm
I'm encountering the same issue MojoMark was (though with a different external application). MojoMark's follow up comment is correct, the read_text information does not answer the question.
Like MojoMark, I am attempting to RECEIVE a POST from an external entity. The PLSQL I'm trying to write is to receive that POST and store it.
I was able to write the outbound POST XML with no problem, but have been unable to set up a procedure to receive it.
The issue appears to be the PLSQL procedure wants a variable name, ie:
http://server/modplsql/testload, POST "data='data'"
However, the body of the POST is just an XML data stream, no "=" assigning a value to a parameter, so the function gets the "Mismatch or Missing '='"" error.
It seems like there should be a way to tell MODPLSQL to just accept accept the post data like a "typical" function call, but I think I'm missing something obvious.
The basics function I'm trying to use to receive the post is:
procedure testload ( DATA in clob ) as
BEGIN
htp.print('Input POST stream was ' || DATA )
end testload;
The only significant difference I can see between the two requests is the "Expect: 100-continue" business. This appers to be a clause in the HTTP 1.1 specification which allows the client to split the request in two. Basically, the client sends the header to the server, and the server must make a choice. If it is "happy" with the header it will give a HTTP 100 response to indicate that the rest of the message will be accepted.
Since you're getting data from Flickr, I'm not sure what level of control you have over the http requests being made by the client. From the server side it may be necessary to make a configuration change to Apache, or it may be a bug in mod_plsql that's popping up with the "!" flexible parameter marker.
Either way, the current blogger api is not like this. You probably should move to the new GData API.

Resources