You don't need cast at all. The JavaScriptSerializer.Serialize
method has this prototype:
public string Serialize(Object obj)
This means that your "unboxed" model will be boxed again and than you don't have to do this. Internally the function use Reflection and is able to read all Model metadata even it is passed to the method as object.
Using ref
for HttpContext
is not necessary and it is little bit dangerous because HttpContext
is reference type and you can change reference in the called method. I have never seen good reason for pass reference type with ref keyword. It is useful mainly with value types.
Your solution can looks like:
public static void WriteResponse(HttpContext ctx, object model)
{
string jsonObject = new JavaScriptSerializer().Serialize(model);
ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
ctx.Response.ContentType = "Content-type: application/json";
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.Write(jsonObject);
}
Second point is that you don't have to cast model to object
and you can pass model directly:
ShapefileService.WriteResponse(ctx, model);
If you really need strong type in the WriteResponse
method, than you can use generic method:
public static void WriteResponse<T>(HttpContext ctx, T model)
{
string jsonObject = new JavaScriptSerializer().Serialize(model);
ctx.Response.AddHeader("Access-Control-Allow-Origin", "*");
ctx.Response.ContentType = "Content-type: application/json";
ctx.Response.ContentEncoding = Encoding.UTF8;
ctx.Response.Write(jsonObject);
}
ShapefileService.WriteResponse<Models.SfShortInfo>(ctx, model);