Web API with ASPNet Core
Now that I've taken the jump to Web API, I wanted a simple reusable logic that I could use to communicate with any of my Web API's.
There are two main reusable code I use is using the WebRequest and WebClient (Download string) logic. Below I will show the reusable code I find very useful

Reusable code Example 1 (WebRequest )

Full code snippet
The below snippet is the full class, I use and reuse when communicating with a Web API.
This class does need the below using references:
using System.Web.Script.Serialization; (This needs the System.Web.Extensions reference)

public class JSONAPI
{
public static bool CallBoolReturn(string url, string requestMethod, object dataObject)
{
bool boolreturn = false;
string response = Call(url, requestMethod, dataObject);
bool.TryParse(response, out boolreturn);
return boolreturn;
}

public static object CallSameReturn(string url, string requestMethod, object dataObject)
{
string response = Call(url, requestMethod, dataObject);
return jsonToObject(response, dataObject.GetType());
}

public static object CallDifferentReturn(string url, string requestMethod, object dataObject, Type returnType)
{

object returnObject = null;

string response = Call(url, requestMethod, dataObject);

if (response != null)
returnObject = jsonToObject(response, returnType);

return returnObject;
}
public static string Call(string url, string requestMethod, object dataObject)
{
try
{
HttpWebRequest request = createRequest(url, requestMethod, dataObject);
if (request != null)
{
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
Console.Out.WriteLine(response);
responseReader.Close();

return response;// jsonToObject(response, dataObject.GetType());
}

}
catch (Exception e)
{

}

return null;

}

private static HttpWebRequest createRequest(string url, string requestMethod, object dataObject)
{
HttpWebRequest request = null;
try
{
string jsonDataString = new JavaScriptSerializer().Serialize(dataObject);

request = (HttpWebRequest)WebRequest.Create(url);
request.Method = requestMethod;// "POST";
request.ContentType = "application/json";
request.ContentLength = jsonDataString.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
requestWriter.Write(jsonDataString);
requestWriter.Close();



}
catch (Exception e)
{

}

return request;
}

private static object jsonToObject(string response, Type dateType)
{

object jsonDataObject = new JavaScriptSerializer().Deserialize(response, dateType);
return jsonDataObject;


}
}



Calling Web API
Using the JSONAPI class, you can simply call any Web API using the below syntax.
CONTROLLERNAME - Replace this with your required API controller.
ACTIONNAME - Replace this with your required API action, within your controller.
POST - This is only telling the logic that its a Post request, You could replace this with GET, PUT or just leave it with POST.


DataParameterDataClass dataParameters = new DataParameterDataClass(){ User = "Test" };
string url = "http://SiteAddress/api/CONTROLLERNAME/ACTIONNAME";
return (DataParameterDataClass)JSONAPI.CallSameReturn(url, "POST", dataParameters);





The above API call is using the method CallSameReturn. This method is used if the parameter class is the same for the return.
The best thing I find with Web APIs, is that your data class only needs to contain parameter names that match the parameter being returned.

CallBoolReturn - This can take any object, but the return object needs to be a bool.
CallDifferentReturn - This is the same as the CallSameReturn, but the return object does not need to be the same as the one being sent.

Reusable code Example 2 (WebClient)
This logic is simpler that the first and seems to work as well.
You do need to Reference Newtonsoft.Json and System.Web.Extentions run the code
Install the NuGet Newtonsoft.Json.


using(var client = new WebClient())
{
string aPIURL = https://www.mysite.com/api/apipostaction?{0}
string id = "101010";
string extraAction = "runMe";
string formatedURL = String.Format(aPIURL, "id={0}&extraaction={1}");
formatedURL = String.Format(formatedURL, id , extraAction);

var reply = client.DownloadString(formatedURL);

DataClass.ResponseDataClass responseDataObject = new DataClass.ResponseDataClass ();

object jsonDataObject = new JavaScriptSerializer().Deserialize(reply, responseDataObject.GetType());
responseDataObject = (DataClass.ResponseDataClass )jsonDataObject

return jsonDataObject;


return responseDataObject.Success;
}


The data class

using Newtonsoft.Json;

public class ResponseDataClass
{
[JsonProperty("success")]
public bool Success { get; set; }

[JsonProperty("error-codes")]
public List<string> ErrorCodes { get; set; }
}

Created: 07/04/2017 Total Comment: 0

Comments

(Not Displayed)
Human validation
Enter 3956 number, before submitting to confirm your human
[Home] [All Blogs] [Contact] [Me]