I'm having trouble getting a number from Random.org. I am following their API, and I believe I have constructed the request correctly. Here is the request code:
self.GetResults = function () {
$.ajax({
url: 'https://api.random.org/json-rpc/1/invoke',
dataType: "json",
contentType: "application/json-rpc; charset=utf-8",
type: 'POST',
data: {
"jsonrpc": "2.0",
"method": "generateIntegers",
"params": {
"apiKey": "Get-a-free-one-at-the-site",
"n": 1,
"min": 1,
"max": 20
},
"id": 1
}
})
.done(function (data, status, request)
{
alert("Success! " + data[0]);
})
.fail(function (request, status, error)
{
alert("Failed " + error);
});
}
The problems I am having are as follows:
- If I don't include
contentType: "application/json; charset=utf-8"
then the default type is"application/x-www-form-urlencoded; charset=UTF-8"
, per the jQuery API documentation. Random.org states in their API that they require a JSON request (application/json-rpc specifically, but application/json is acceptable). I therefore get a parse error in response. - If I do include the content type mentioned above, I get the error, "Request header field Content-Type is not allowed by Access-Control-Allow-Headers."
I have tried to add code to the web.config to allow the request header as follows:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
</customHeaders>
</httpProtocol>
From this post https://stackoverflow.com/a/12413863/981202, but have had no luck.
I've also tried modifying the Global.asax as follows:
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("Access-Control-Allow-Headers");
}
As in another Stack Overflow post (I don't have the link), but that didn't seem to do it either. For clarity, I put this function after the Application_Start() function.
You may be wondering why I don't just use the Random class. The reason is because I'd like to use Random.org if nothing else then as an exercise. I'd like to find a solution to this problem if one exists. Previously, I had some data here that indicated that the C# Random class didn't do a very good job, but I was corrected, so that data has been removed. Yes, the Random class is an option, though as I mentioned, I'd like to find a solution to this problem.