While we are developing Web API, we might expect the caller to pass in either an object or array of object. Of course it would be best to handle array of object as the API paramter. But, we are not always have the luck to change the API parameter type since the existing system is connected by many third party apps.
Basically, the existing code is handling the incoming parameter that is string type, a JSON formatted value. We are parse it correctly if we know that type:
using Newtonsoft.Json.Linq;
string s = @"{'name': 'MIKE', 'age':'23'}";
JObject jobj = JObject.Parse(s);
string s2 = @"[{'name': 'MIKE', 'age':'23'}, {'name': 'MICKEY', 'age':'25'}]";
JArray jarr = JArray.Parse(s2);
Let's say, we modified our Web API to handle array of object while the existing code is only handling object, it will crash:
try
{
// let's crash it
JObject jobj2 = JObject.Parse(s2);
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
In this case, you have to parse the incoming text into JToken.
JToken jt = JToken.Parse(s);
JToken jt2 = JToken.Parse(s2);
To identify whether it is JObject or JArray:
bool b = jt is JObject;
bool b2 = jt is JArray;
Thursday, November 28, 2019
Tuesday, February 26, 2019
Removing some HTTP response headers
In the web.config of ASP.NET website project:
1. Add the following line to remove the X-AspNet-Version header.
<system.web>
<httpRuntime enableVersionHeader="false"/>
</system.web>
2. Removing X-Powered-By header.
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
3. Removing Server header which you may do it in the global.asax
void Application_BeginRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
if (application != null && application.Context != null)
{
application.Context.Response.Headers.Remove("Server");
}
}
To change the default cookie name in ASP.Net
<sessionState cookieName="mySessID" />
Subscribe to:
Posts (Atom)