NULL parsing JSON with NewtonSoft - json-deserialization

THE JSON STRING IS:
{ "errcode" : "0",
"errmsg" : SUCCESS",
"responseObject" :{ "result" :[{ "sjmj" : "ABCD",
"zzmmzw" : NULL,
}], "total" : 39 }}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Headers.Set("userKey", "vsc30r8f");
request.Proxy = null;
request.KeepAlive = false;
request.Method = "GET";
request.ContentType = "application/json; charset=UTF-8";
request.Accept = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
if (response != null)
{
response.Close();
}
if (request != null)
{
request.Abort();
}
when i using Newtonsoft method in c# the code below
JObject jObj111 = JsonConvert.DeserializeObject(retString );
the application exception says"Newtonsoft.Json.JsonReaderException: Error parsing NaN value".
or i use
JObject jObj111 = JObject.Parse(retString )
the also application exception says"Newtonsoft.Json.JsonReaderException: Error parsing NaN value".
how can i solve the prblem thanks very much**

the retString is : { "errcode" : "0", "errmsg" : SUCCESS", "responseObject" :{ "result" :[{ "sjmj" : "ABCD", "zzmmzw" : NULL}], "total" : 39 }}

Related

User.Identity.IsAuthenticated always false when calling from restSharp

I have a web application in which I was authenticating user like below
$.ajax({
method: 'POST',
data: JSON.stringify(SaveDetails),
url: Utils.getWebApiUrl() + "/api/account/isLoggedIn",
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'bearer ' + access_token);
}
})
code in the controller below
[HttpPost]
[Route("api/account/isLoggedIn")]
public IHttpActionResult IsLoggedIn(Dictionary<string, string> Parameters)
//(string UserLoginLogId)
{
if (User?.Identity?.IsAuthenticated == true)
{
if (Parameters.Count() > 0)
{
string userLoginLogId = Convert.ToString(Parameters["UserLoginLogId"]);
string userRefreshToken = Convert.ToString(Parameters["userRefreshToken"]);
if (!string.IsNullOrWhiteSpace(userLoginLogId))
{
DocPro.DMS.BusinessLayer.IAccess.IUser a = (DocPro.DMS.BusinessLayer.IAccess.IUser)DALFinder.GetInstance(typeof(DocPro.DMS.BusinessLayer.IAccess.IUser));
//int LoginTimeOut = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Login-TimeOut"]);
if (a.IsLoggedInAsPerRefreshToken(Convert.ToInt64(userLoginLogId), userRefreshToken))
return Ok();
else
return NotFound();
}
else
return NotFound();
}
else
return Ok();
}
else
return NotFound();
}
and it was working fine, now I changed the code to the following
Dictionary<string, string> p = new Dictionary<string, string>();
p.Add("UserLoginLogId", Convert.ToString(userId));
p.Add("userRefreshToken", Convert.ToString(RefreshToken));
RestClient client = new RestClient(Convert.ToString(URL));
client.Timeout = -1;
RestRequest request = new RestRequest(Method.POST);
request.RequestFormat = DataFormat.Json;
request.AddJsonBody(p);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + accessToken);
IRestResponse<SPResponse> response = client.Execute<SPResponse>(request);
var result = JsonConvert.DeserializeObject<SPResponse>(response.Content);
but the following key "User?.Identity?.IsAuthenticated" is always showing false and I don't understand the reason.
while I do google I found a solution like below
var isAusorized = (Request.Properties["MS_HttpContext"] as HttpContextWrapper).User.Identity.IsAuthenticated;
but I don't understand how it worked and should I use this or not.

Swashbuckle - How to omit only REST api methods, but not Entities

We use swashbuckle to generate client code where we need only model class types, but not methods which are generated to call api. For that we have our own generic implementation. Is there a way how to omit those methods only without omitting model classes?
When I use [ApiExplorerSettings(IgnoreApi = true)] on all my controllers, my output js file is empty.
For example it generates these methods, which are completly useless for us, only what I need is Metadata class type, nothing else.
apiGet(): Promise<Metadata> {
let url_ = this.baseUrl + "/api/MetadataRepository/Catalog";
url_ = url_.replace(/[?&]$/, "");
let options_ = <RequestInit>{
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processApiGet(_response);
});
}
protected processApiGet(response: Response): Promise<Metadata> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = resultData200 ? Metadata.fromJS(resultData200) : new Metadata();
return result200;
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<Metadata>(<any>null);
}

Web api 2 - Async Post

I'm develop a web api2 where I post json data.
The code of this api is:
public HttpResponseMessage Post(an_lavanderie an_lavanderie)
{
var response = new HttpResponseMessage();
if (!ModelState.IsValid)
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("modello non valido"));
}
bool creato = _repoLavanderie.CreaLavanderia(an_lavanderie);
if (creato == true)
{
response = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
response = Request.CreateErrorResponse(HttpStatusCode.NotFound, new Exception("Errore nella creazione"));
}
return response;
}
This code write into db correctly.
My code to POST DATA is this:
var risultato = PostDataAsync();
and the function is
var lav1 = new Lavanderia()
{
rag_soc = "Ragione Sociale",
rag_soc2 = "Ragione sociale2",
indirizzo = "Via Crispi 27",
citta = "Ovada",
provincia = "AL",
isAttiva = "N",
portalkey = "sample string 1",
isPortalVisibile = "S",
cap = "15057"
};
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:56040/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.PostAsJsonAsync("api/CreaLavanderia", lav1);
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
MessageBox.Show("Crezione effettuata correttamente");
}
else
{
MessageBox.Show("Creazione non effettuata");
}
}
return "";
Post operation is ok, but when await don't fire.
Is possible that the return Message from webapi is not correct?
Where is the problem?
Thanks.
Since you are using await and you're saying that it's not firing make sure that your method is marked with the keyword async.

Google Site Verification API

I am trying to develop Google site verification system using ASP.Net. Also using the Google explorer (https://developers.google.com/site-verification/v1/webResource/insert) to test the request method such as JSON and HTTP request format.
This is what I am sending to the Google.
POST https://www.googleapis.com/siteVerification/v1/webResource?verificationMethod=site&key={YOUR_API_KEY}
Content-Type: application/json
Authorization: Bearer xxxxxxxxxxxxxxx
X-JavaScript-User-Agent: Google APIs Explorer
{
"id": "myid",
"owners": [
"development#gmail.com"
],
"site": {
"type": "site",
"identifier": "http://www.example.net/"
}
}
I am getting following response from the Google.
{
"error": {
"errors": [
{
"domain": "global",
"reason": "backendError",
"message": "Backend Error"
}
],
"code": 503,
"message": "Backend Error"
}
}
>
IAuthorizationState authorization;
protected void Page_Load(object sender, EventArgs e)
{
if (googleClient != null)
{
if (IsPostBack)
{
authorization = googleClient.ProcessUserAuthorization();
if (authorization != null)
{
this.AccessToken = authorization.AccessToken;
}
else if (this.AccessToken == null)
{
googleClient.RequestUserAuthorization(scope: new[] { GoogleClient.Scopes.WebMaster.SiteVerification });
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (authorization != null)
{
IOWebMasterInsertGraph webMasterInsertGraph = googleClient.RequestForVerification(authorization);
}
}
public IOWebMasterInsertGraph RequestForVerification(IAuthorizationState authState)
{
if ((authState != null) && (authState.AccessToken != null))
{
WebRequest request = WebRequest.Create("https://www.googleapis.com/siteVerification/v1/webResource?verificationMethod=site");
string path = HostingEnvironment.MapPath(#"~/App_Data/GoogleInsert.json");
MemoryStream ms = new MemoryStream();
FileStream fileStreem = new FileStream(path, FileMode.Open, FileAccess.Read);
byte[] bytes = new byte[fileStreem.Length];
fileStreem.Read(bytes, 0, (int)fileStreem.Length);
ms.Write(bytes, 0, (int)fileStreem.Length);
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = ms.Length;
ms.Seek(0, SeekOrigin.Begin);
using (Stream requestStream = request.GetRequestStream())
{
ms.CopyTo(requestStream);
}
WebResponse response = request.GetResponse();
if (response != null)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
//return GoogleGraph.Deserialize(responseStream);
return WebMasterInsertGraph.Deserialize(responseStream);
}
}
}
return null;
}
Does anyone know the reason for this?
Why don't you use the Google .NET client library for Site verification?
You even have a sample code for that.
Try it out...
I have found the answer myself.
The following has to be sent to the GoogleApi without the id in JSON. The verificationMethos has to be one you selected when getting token.
POST /siteVerification/v1/webResource?verificationMethod=file HTTP/1.1 Host: www.googleapis.com
Content-length: 138
Content-type: application/json
Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
{
"owners": [
"sample#gmail.com" ],
"site": {
"identifier": "http://test.sample.com/",
"type": "SITE" }
}

upload serialized data using WebClient

Simple requirement . I have a class - User - {userId, userName, age}.
How to serailize a object of the class and sent to a url (using post) using webclient.
Something Like below.
What is the best way to serialise user object into postdata format.
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.Credentials = CredentialCache.DefaultNetworkCredentials;
string postData = "orderId=5&status=processed2&advertId=ADV0001a";
byte[] postArray = Encoding.ASCII.GetBytes(postData);
client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
byte[] responseArray = client.UploadData(address, postArray);
var result = Encoding.ASCII.GetString(responseArray);
return result;
I would apply the following simplification to your code:
using (var client = new WebClient())
{
client.Credentials = CredentialCache.DefaultNetworkCredentials;
var data = new NameValueCollection
{
{ "userId", user.Id },
{ "userName", user.Name },
{ "age", user.Age }
};
var responseArray = client.UploadValues(address, data);
return Encoding.ASCII.GetString(responseArray);
}

Resources