Introduction
The aim is to create a simple response object from Web services which will have:
- A generic data holder to hold specific typed data
- A flag to trace if the execution completed without any error or not
- If there is any error, store the exception too.
Background
Here is the simple response object, which has a generic container to hold data.
public class Response<TSource>
{
public readonly bool IsSuccess;
public readonly TSource Data;
public readonly Exception Exception;
private Response()
{
Data = default(TSource);
Exception = null;
}
private Response(bool isSuccess)
: this()
{
IsSuccess = isSuccess;
}
public Response(TSource data)
: this(true)
{
Data = data;
}
public Response(Exception exception)
: this(false)
{
Exception = exception;
}
}
Using the Code
We can use this response object like:
Response<string> response = null;
response = new Response<string>("Hello World");
response = new Response<string>(new Exception("Error."));
Response<Exception> response1 = null;
response1 = new Response<Exception>
(new Exception("Error."));
Using it in ASP.NET MVC:
public JsonResult GetAll()
{
Response<List<Student>> response = null;
try
{
List<Student> students = _logic.Get();
response = new Response<List<Student>>(students);
}
catch
{
response = new Response<List<Student>>(new Exception("Error."));
}
return Json(response);
}
Using it in Web Service:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Get(string name)
{
Response<Student> response = null;
try
{
Student student = _logic.Get(name);
response = new Response<Student>(student);
}
catch
{
response = new Response<Student>(new Exception("Error."));
}
return new JavaScriptSerializer().Serialize(response);
}
Or with any method:
public Response<String> Get(string name)
{
return Response<Student>("done");
}
Find the VS2010 console project solution in the attachment.