I am building a web service that gets data via Stored Procedures from a db and provides the result as JSON. The solution is built as a MVC 4 Web API project. I have to retrieve the data via Stored Procedures for several reasons (security, SQLAnywhere db, etc).
It is a relatively small scale project so I have opted for not defining a Model in the Web Service layer to save work (and possibly performance). There will likely be models in the front end application (which will be a MVC 4 Web Application).
The reasons why I am including an extra layer in the form of a Web Service is to a) add extra security, and b) that there will likely be a iPhone app for part of the application which then can utilize the same web service as the site.
It is working as I want it to, so what I want feedback on is
- What do you think of the general approach to build a MVC 4 Web API solution without explicit models?
- Do you have any comments on how to improve the details of the implementation?
One potential thought I have had is to skip the dataset and make a direct call to the Stored Procedure and loop over a datareader, which could potentially be faster. The other potential change is to loop over the datatable and build up the JSON manually instead of using the serializer.
What I like about the current solution is that it can be done on very few lines of code and that I do not have to manually name each JSON object since it is inherited from the datatable within the dataset.
I define a dataset called dsProducts that is loaded with a TableAdapter.
// GET api/products
public string Get()
{
string result = "";
dsProductTableAdapters.GetProductsTableAdapter taTemp = new dsProductsTableAdapters.GetProductsTableAdapter();
dsProducts dsTemp = new dsProducts();
try {
taTemp.Fill(dsTemp.GetProducts);
result = jsonHelper.convertJSONString(dsTemp.GetProducts);
} catch (Exception ex) {
result = "{\"error\":\"1\"}";
}
return result;
}
The convertJSONString and its help functions are defined as:
public static string convertJSONString(DataTable table)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(table.ToDictionary());
}
static Dictionary<string, object> ToDictionary(this DataTable dt)
{
return new Dictionary<string, object> {
{ dt.TableName, dt.convertTableToDictionary() }};
}
static object convertTableToDictionary(this DataTable dt)
{
var columns = dt.Columns.Cast<DataColumn>().ToArray();
return dt.Rows.Cast<DataRow>().Select(r => columns.ToDictionary(c => c.ColumnName, c => r[c]));
}
taTemp
anddsTemp
are both objects of classes which implementIDisposable
and therefore should be wrapped inusing
statements to ensure proper deterministic disposal. \$\endgroup\$