how to send Content-Disposition: form-data; name="name" in correct way when call post api from C# to avoid statuserror 500 - xmlhttprequest

public async Task<T> PostFrom<T>(string baseAddress, string url, string requestbody)
{
T obj = default(T);
//Create the Uri string
string request = baseAddress + url;
WriteLog(request + " : " + "start");
try
{
//Create the Uri
var urirequest = new Uri(request);
//define MultipartFormDataContent
var multipart = new MultipartFormDataContent();
//Add Content-Type
multipart.Headers.Remove("Content-Type");
multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + financialAuth.Value.ContentType.boundary);
//Add AuthToken
multipart.Headers.Add("AuthToken", financialAuth.Value.AuthToken);
//start adding the Content-Disposition which i have 3 of them
//1st Content-Disposition form-data; name="SearchCriteria" "requestbody" is the json
if (!string.IsNullOrEmpty(requestbody))
{
var requestbodyContent = new StringContent(JsonConvert.SerializeObject(requestbody));
requestbodyContent.Headers.Add("Content-Disposition", "form-data; name=\"SearchCriteria\"");
multipart.Add(requestbodyContent, "SearchCriteria");
}
//2nd Content-Disposition form-data; name="Secret" "financialAuth.Value.Secret" is the string
var secretContent = new StringContent(financialAuth.Value.Secret);
secretContent.Headers.Add("Content-Disposition", "form-data; name=\"Secret\"");
multipart.Add(secretContent, "Secret");
//3rd Content-Disposition form-data; name="AppID" "financialAuth.Value.AppID" is the string
var appIdContent = new StringContent(financialAuth.Value.AppID);
appIdContent.Headers.Add("Content-Disposition", "form-data; name=\"AppID\"");
multipart.Add(appIdContent, "AppID");
//define the HttpRequestMessage of type post
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, urirequest);
//assign the multipart of httpRequestMessage.Content
httpRequestMessage.Content = multipart;
//assign the urirequest of httpClient.BaseAddress
client.BaseAddress = urirequest;
WriteLog("start url" + request);
/* Here when I call the post web api I'm getting below error:
{{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.HttpConnection+HttpConnectionResponseContent,
Headers: {
Cache-Control: no-cache
Pragma: no-cache
Server: Microsoft-IIS/8.5
X-AspNet-Version: 4.0.30319
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,authtoken
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Date: Tue, 26 Feb 2019 14:59:51 GMT
Content-Type: application/json; charset=utf-8
Expires: -1
Content-Length: 36
}}
*/
HttpResponseMessage response = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);
WriteLog("END url" + request);
if (response.IsSuccessStatusCode)
{
WriteLog(request + " : " + "Begin Result");
string result = await response.Content.ReadAsStringAsync();
obj = JsonConvert.DeserializeObject<T>(result);
WriteLog(request + " : " + "End Result");
}
}
catch (Exception ex)
{
WriteLog(request + " " + ex.Message);
}
return obj;
}

I just solved the error by commenting the below code:
// Add Content-Type
multipart.Headers.Remove("Content-Type");
multipart.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + financialAuth.Value.ContentType.boundary);
It seems the content type will be created automatically by MultipartFormDataContent.
Thanks for looking into my issue.

Related

failed-network error when downloading excel file

I have a button that will open a new window using javascript window.open to download an excel file, but chrome always shows "Failed-Network error."
The same code is running in another action, and it works fine.
var stream = new MemoryStream();
using (var package = new ExcelPackage(stream))
{
var workSheet = package.Workbook.Worksheets.Add("Sheet1");
workSheet.Cells["G1:J1"].Merge = true;
workSheet.Cells["G1:J1"].Value = "Translations";
workSheet.Cells["A2"].Value = "Key Name";
workSheet.Cells["B2"].Value = "Key Description";
workSheet.Cells["C2"].Value = "Key Type";
workSheet.Cells["D2"].Value = "Applications";
workSheet.Cells["E2"].Value = "English Text";
workSheet.Cells["F2"].Value = "Status";
workSheet.Cells["G2"].Value = "Arabic";
workSheet.Cells["H2"].Value = "French";
workSheet.Cells["I2"].Value = "Portugese";
workSheet.Cells["J2"].Value = "Spanish";
for (int i = 0; i < result.Data.Count; i++)
{
var currentKey = result.Data[i];
workSheet.Cells[i + 3, 1].Value = currentKey.Name;
workSheet.Cells[i + 3, 2].Value = currentKey.Description;
workSheet.Cells[i + 3, 3].Value = currentKey.LabelName;
workSheet.Cells[i + 3, 4].Value = string.Join(',',
appBL.GetLocalizationKeyApplicationNames(currentKey.Id).Data);;
workSheet.Cells[i + 3, 5].Value =
currentKey.EnglishTranslation;
workSheet.Cells[i + 3, 6].Value = currentKey.Status;
var translations = currentKey.Translations;
workSheet.Cells[i + 3, 7].Value =
translations.FirstOrDefault(t => t.Language ==
LanguageEnum.Arabic).Value;
workSheet.Cells[i + 3, 8].Value =
translations.FirstOrDefault(t => t.Language ==
LanguageEnum.French).Value;
workSheet.Cells[i + 3, 9].Value =
translations.FirstOrDefault(t => t.Language ==
LanguageEnum.Portuguese).Value;
workSheet.Cells[i + 3, 10].Value =
translations.FirstOrDefault(t => t.Language ==
LanguageEnum.Spanish).Value;
}
package.Save();
}
Response.Headers.Add("Content-Disposition",
string.Format("attachment;filename={0}",
$"localization keys-{DateTime.Now.ToString("yyyyMMdd")}"
+ ".xlsx"));
Response.Headers.Add("Transfer-Encoding", "identity");
Response.ContentLength = stream.Length;
return File(stream, "application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet",
$"localization keys-
{DateTime.Now.ToString("yyyyMMdd")}.xlsx");
here is the request and response headers for the call
Request Headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:44374
Pragma: no-cache
Referer: https://localhost:44374/
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: same-origin
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Response Headers:
Content-Disposition: attachment; filename="localization keys-20210103.xlsx"; filename*=UTF-8''localization%20keys-20210103.xlsx
Content-Length: 2731
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Date: Sun, 03 Jan 2021 06:44:15 GMT
Server: Microsoft-IIS/10.0
Transfer-Encoding: identity
X-Powered-By: ASP.NET
Any thoughts?
Thank you.
I just ran into the same issue, the solution relies in the front-end on your javascript, I would love to help you more, and I am willing to edit my response with a sample that relates to your code, if you could post your javascript on your original question.
for now I can give you the link that help me resolve my issue, it is not straight forward and again I am willing to give you a better answer if you can provide your javascript code.
Problems downloading big file(max 15 mb) on google chrome
and my implementation looks like this:
function saveAsFile(filename, bytesBase64) {
var data = window.atob(bytesBase64);
var bytes = new Uint8Array(data.length);
for (var i = 0; i < data.length; i++) {
bytes[i] = data.charCodeAt(i);
}
var blob = new Blob([bytes.buffer], { type: "application/octet-stream" });
var url = URL.createObjectURL(blob);
var link = document.createElement('a');
link.download = filename;
link.href = url;
document.body.appendChild(link); // Needed for Firefox
link.click();
document.body.removeChild(link);
}
i found the solution, i needed to set the position of the stream to 0
stream.Position = 0;

CKEDITOR File Upload Bad Request 400 Error

I am using ckEditor with the file browser, filemanager plugin in it. What i am trying to achieve when i configure the CKeditor I am able to browse the file in a certain folder .. but when i try to upload the file through it I am getting an error of 400 Bad Request may be there is something which I need to do ?
Following is my code
[HttpPost]
CKEDITOR.replace('content_editor',{
customConfig: '/assets/back/dist/plugins/ckeditor/config.js',
"imageBrowser_listUrl" : "/webmaster/files/browser"
});
CKEDITOR.on('fileUploadRequest', function (evt) {
var fileLoader = evt.data.fileLoader,
formData = new FormData(),
xhr = fileLoader.xhr;
xhr.open( 'PUT', fileLoader.uploadUrl, true );
formData.append( 'upload', fileLoader.file, fileLoader.fileName );
fileLoader.xhr.send( formData );
// Prevented the default behavior.
evt.stop();
} );
Request Handler C# ASP.NET CORE 3.1
public async Task<IActionResult> UploadFromEditor([FromForm]IFormFile upload)
{
if (upload.Length <= 0) return null;
if (!upload.IsImage())
{
var NotImageMessage = "please choose a picture";
dynamic NotImage = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + NotImageMessage + "\"}}");
return Json(NotImage);
}
var fileName = Guid.NewGuid() + Path.GetExtension(upload.FileName).ToLower();
Image image = Image.FromStream(upload.OpenReadStream());
int width = image.Width;
int height = image.Height;
if ((width > 750) || (height > 500))
{
var DimensionErrorMessage = "Custom Message for error";
dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + DimensionErrorMessage + "\"}}");
return Json(stuff);
}
if (upload.Length > 500 * 1024)
{
var LengthErrorMessage = "Custom Message for error";
dynamic stuff = JsonConvert.DeserializeObject("{ 'uploaded': 0, 'error': { 'message': \"" + LengthErrorMessage + "\"}}");
return Json(stuff);
}
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/uploads/images/conten_images",
fileName);
using (var stream = new FileStream(path, FileMode.Create))
{
upload.CopyTo(stream);
}
var url = $"{"/uploads/images/CKEditorImages/"}{fileName}";
var successMessage = "image is uploaded successfully";
dynamic success = await Task.Run(() => JsonConvert.DeserializeObject("{ 'uploaded': 1,'fileName': \"" + fileName + "\",'url': \"" + url + "\", 'error': { 'message': \"" + successMessage + "\"}}"));
return Json(success);
}
Extra Plugins code :
CKEDITOR.editorConfig = function( config ) {
config.filebrowserBrowseUrl = '/assets/back/dist/ckeditor/plugins/imagebrowser/browser/browser.html'
config.filebrowserUploadUrl = '/webmaster/files/UploadFromEditor';
config.extraPlugins = 'filetools';
config.extraPlugins = 'uploadimage';
config.extraPlugins = 'popup';
config.extraPlugins = 'imagebrowser';
config.filebrowserUploadMethod = 'xhr';
};
Please help me out here
here are the headers :
XHRPOSThttps://localhost:5001/webmaster/files/UploadFromEditor
[HTTP/2 400 Bad Request 73ms]
POST
https://localhost:5001/webmaster/files/UploadFromEditor
Status400
Bad Request
VersionHTTP/2
Transferred85.50 KB (0 B size)
content-length
0
date
Tue, 03 Nov 2020 09:13:50 GMT
server
Kestrel
X-Firefox-Spdy
h2
Accept
*/*
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
Connection
keep-alive
Content-Length
86268
Content-Type
multipart/form-data; boundary=---------------------------1063707225330149515660008029
Cookie
.AspNetCore.Session=CfDJ8ERqQf6e11lCnNAhOo0wjyavEQJqEJ7gsv1MXMI4QwPk9Px8mznruNuZcxnmuYGnGjs1GtOWQI4DVCXYKd%2FRbNNo62%2FtopzHy%2FxaW87rvNE13QikL84JT0m32Ie1LWSZR3AkxYAE5p4U7TEpN5FccezCSMDeUR9geLW3lSjFIJD4; .AspNetCore.Antiforgery.J7MIrShXchg=CfDJ8ERqQf6e11lCnNAhOo0wjyYadzIaShP7Nt-bl6orx5lTMtnVoGxw8noimjE32qvhp_f96p2Hx4_zK8hzdRIz12615ZdyisBTz6X9HPA39cgIvRTjmWmrWNcLlm4S2MvPAQrG9hofg1ANinWAOwKIyXc; ckCsrfToken=8qZ4KEfRjaBWRmI6coRoRbJrZd8DgYG18gAz86eN; .AspNetCore.Antiforgery.XfkU3LYWHPY=CfDJ8NfGIpF9PVtNgLP3wXt3ZoscmmPZ8ZskVSbYiI69p4lPZYB3mt9mFEqRuOV0Ajfi2f8NNbjcyEHtfta7RlEHTBhXdRfPonXD1sN2EIS2BvcjZCrN8sJXN4UMo_JlolirVt3VIcCTm-wGAtIzGq0150w
Host
localhost:5001
Origin
https://localhost:5001
Referer
https://localhost:5001/webmaster/News/Create
TE
Trailers
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0
X-Requested-With
XMLHttpRequest
Cookie “.AspNetCore.Antiforgery.XfkU3LYWHPY” will be soon treated as cross-site cookie against “https://localhost:5001/webmaster/files/UploadFromEditor” because the scheme does not match. UploadFromEditor
Source map error: Error: request failed with status 404
Resource URL: https://localhost:5001/assets/back/dist/bootstrap/js/bootstrap.min.js
Source Map URL: bootstrap.min.js.map
Based on the details about your test request, it seems that you configured and enabled antiforgery token validation. If JavaScript client not set/include the token in request, which would cause 400 Bad Request error.
To fix it, as I mentioned in comment, we can apply IgnoreAntiforgeryToken Attribute to action method UploadFromEditor to skip antiforgery token validation.
Or set the token in request header to make the request can pass antiforgery token validation.
https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1#javascript

How can I get html code from Webpage with login?

I want to get the HTML Code from a Webpage (German Prepaid Provider).
I tried it with Webrequest but this does not work.
async private void connectToLidlConnect()
{
string user = UserName;
string pass = Password;
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "login=" + user + "&mdp=" + pass;
byte[] data = encoding.GetBytes(postData);
WebRequest request = WebRequest.Create("https://kundenkonto.lidl-connect.de/login.html");
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["ContentLength"] = data.Length.ToString();
using (Stream stream = await request.GetRequestStreamAsync())
{
stream.Write(data, 0, data.Length);
}
using (WebResponse response = await request.GetResponseAsync())
{
using (Stream stream = response.GetResponseStream())
{
using (StreamReader sr = new StreamReader(stream))
{
//
var a = sr.ReadToEnd();
}
}
}
}
How can I navigate to the next page with Cookies?
I Tried this too:
async public Task LogIn()
{
CookieContainer container;
var request = (HttpWebRequest)WebRequest.Create(LoginPageAdress);
request.Method = "PUT";
request.ContentType = "application/x-www-form-urlencoded";
var buffer = Encoding.ASCII.GetBytes(loginData.ToString());
request.Headers["ContentLength"] = buffer.Length.ToString();
var requestStream = await request.GetRequestStreamAsync();
requestStream.Write(buffer, 0, buffer.Length);
container = request.CookieContainer = new CookieContainer();
var request1 = (HttpWebRequest)WebRequest.Create(new Uri("https://kundenkonto.lidl-connect.de/mein-lidl-connect/mein-tarif/uebersicht.html"));
request1.CookieContainer = container;
var webResponse = await request1.GetResponseAsync();
var response = (HttpWebResponse)webResponse;
// Get the stream associated with the response.
Stream receiveStream = response.GetResponseStream();
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
var html = readStream.ReadToEnd();
CookieContainer = container;
requestStream.Dispose();
response.Dispose();
readStream.Dispose();
webResponse.Dispose();
}
But with this I only get the html from the Login page... It seems that i am using the cookiecontainer wrong.
So I got from Fiddler this Information (I Changed my LoginData Username=xxxxxxxxxxx; Password XXXXXXXXXXXX):
POST ttps://kundenkonto.lidl-connect.de/login.html HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, /
Referer: ttps://kundenkonto.lidl-connect.de/login.html
Accept-Language: de-DE
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate, br
Host: kundenkonto.lidl-connect.de
Content-Length: 109
Connection: Keep-Alive
Cache-Control: no-cache
Cookie: resolution=1440; PHPSESSID=td1ee0rkkv7qr72ku6ilk1gq55
lastpage=1&REQUEST_TOKEN=51ae54e320c2cc7aa64302be163a0c5a&msisdn_msisdn=xxxxxxxxxxx&password=XXXXXXXXXXXX
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text / html, application / xhtml + xml, image / jxr");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding","gzip, deflate");
client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Language"," de-DE");
client.DefaultRequestHeaders.TryAddWithoutValidation("User - Agent", "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 52.0.2743.116 Safari / 537.36 Edge / 15.15063");
maybe someone can help me:)
Thank You :)

CRM 2016 api unauthorized access

I wrote this code to connect to CRM on premise 2016 and retrieve some data.
Here it's
var credentials = new NetworkCredential("username", "password?", "domain");
var client = new HttpClient(new HttpClientHandler() { Credentials = credentials })
{
BaseAddress = new Uri("https://xxxtestenv.elluciancrmrecruit.com/api/data/v8.0/")
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("datatel_events?$orderby=datatel_eventname").Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsStringAsync();
}
but I get this error
response {StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
REQ_ID: b685b007-199b-4a4a-85cc-3a29684e5588
Date: Thu, 22 Sep 2016 19:27:35 GMT
Server: Microsoft-IIS/8.5
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
Connection: keep-alive
Content-Length: 49
Content-Type: text/plain
}} System.Net.Http.HttpResponseMessage
Any suggestions?
Try using below code to connect to MS CRM on premise.
string strOrganizationUri = "https://{your domain}/XRMServices/2011/Organization.svc";
string strUserName = "{your domain username}";
string strPassword = "{your domain password}";
var organizationUriIFD = new Uri(strOrganizationUri);
var credentials = new ClientCredentials();
credentials.UserName.UserName = strUserName;
credentials.UserName.Password = strPassword;
IServiceConfiguration<IOrganizationService> config = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(organizationUriIFD);
IOrganizationService service;
using (var serviceProxy = new OrganizationServiceProxy(config, credentials))
{
// This statement is required to enable early-bound type support.
serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
service = serviceProxy;
}
// Get the ID's of the current user and business unit.
var who = new WhoAmIRequest();
//retreive user data from the server.
var whoResponse = (WhoAmIResponse)service.Execute(who);

412 Response on second request to Github

I'm getting some very strange behavior using AFNetworking 2.0 to access the Github API. The first time I make an API request to this end point http://developer.github.com/v3/oauth/#get-or-create-an-authorization-for-a-specific-app to get the OAuth token, it comes back with a 200 or 201 response like it should. If I quit the application and try again, the request comes back with a 412 response, even though the requests are identical. I have not been able to reproduce this using curl. I'll paste the requests and responses here.
Request response 1 that passes
PUT 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Basic ****************************";
"Content-Type" = "application/json; charset=utf-8";
"User-Agent" = "Staticly/1.0 (iPad Simulator; iOS 7.0.3; Scale/1.00)";
} {"client_secret":"*****************************","scope":["repo"]}
2014-01-08 10:43:26.313 Staticly[6035:70b] PUT 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Basic **************************";
"Content-Type" = "application/json; charset=utf-8";
"User-Agent" = "Staticly/1.0 (iPad Simulator; iOS 7.0.3; Scale/1.00)";
} {"client_secret":"*******************************","scope":["repo"]}
2014-01-08 10:43:26.364 Staticly[6035:70b] 200 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d' [0.0510 s]: {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Origin" = "*";
"Access-Control-Expose-Headers" = "ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval";
"Cache-Control" = "private, max-age=60, s-maxage=60";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=utf-8";
Date = "Wed, 08 Jan 2014 15:43:24 GMT";
Etag = "\"257ff8977266fd375142f862e0536b53\"";
Server = "GitHub.com";
Status = "200 OK";
"Transfer-Encoding" = Identity;
Vary = "Accept, Authorization, Cookie, X-GitHub-OTP, Accept-Encoding";
"X-Content-Type-Options" = nosniff;
"X-GitHub-Media-Type" = "github.beta";
"X-GitHub-Request-Id" = "633B6CDC:6F7C:9F9595F:52CD721C";
"X-RateLimit-Limit" = 5000;
"X-RateLimit-Remaining" = 4985;
"X-RateLimit-Reset" = 1389198563;
} (null)
Request response 2 that fails
PUT 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Basic *********************";
"Content-Type" = "application/json; charset=utf-8";
"User-Agent" = "Staticly/1.0 (iPad Simulator; iOS 7.0.3; Scale/1.00)";
} {"client_secret":"************************","scope":["repo"]}
2014-01-08 10:45:39.187 Staticly[6078:70b] PUT 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d': {
"Accept-Language" = "en;q=1, fr;q=0.9, de;q=0.8, zh-Hans;q=0.7, zh-Hant;q=0.6, ja;q=0.5";
Authorization = "Basic ***************************";
"Content-Type" = "application/json; charset=utf-8";
"User-Agent" = "Staticly/1.0 (iPad Simulator; iOS 7.0.3; Scale/1.00)";
} {"client_secret":"*************************","scope":["repo"]}
2014-01-08 10:45:39.188 Staticly[6078:70b] 412 'https://api.github.com/authorizations/clients/a162f34fd261c382b59d' [0.0018 s]: {
"Access-Control-Allow-Credentials" = true;
"Access-Control-Allow-Origin" = "*";
"Access-Control-Expose-Headers" = "ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval";
"Cache-Control" = "private, max-age=60, s-maxage=60";
"Content-Type" = "text/html;charset=utf-8";
Date = "Wed, 08 Jan 2014 15:45:37 GMT";
Etag = "\"257ff8977266fd375142f862e0536b53\"";
Server = "GitHub.com";
Status = "412 Precondition Failed";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-GitHub-Request-Id" = "633B6CDC:6F7A:91EF162:52CD72A1";
"X-RateLimit-Limit" = 5000;
"X-RateLimit-Remaining" = 4983;
"X-RateLimit-Reset" = 1389198563;
} (null)
I figured this one out after digging through the OctoKit source code. Github didn't like the caching policy set by [NSURLSessionConfiguration defaultSessionConfiguration]. Setting the caching policy to NSURLRequestReloadIgnoringLocalCacheData fixed the issue.