1. For the returned JSON object format is "Pascal" style (such as "FirstName"), however our API is very likely to be consumed by the client with JavaScript, for JS developers may be more suitable for "hump" style (e.g. "FirstName" ) data. Solution: Configure JSON format.
The WEB API provides XML and JSON as the format for returning data, and the framework automatically injects those formats into the pipeline. The client can declare the desired data format through the HTTP request header, and we can configure the JSON data format by using the "Webapiconfig" class:
public static class Webapiconfig {public static void Register (Httpconfiguration config) { Web API configuration and services var json = CONFIG.
Formatters.jsonformatter; A circular reference problem JSON when resolving JSON serialization.
serializersettings.referenceloophandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; get rid of XML Serializer config. Formatters.remove (config.
Formatters.xmlformatter); var jsonformatter = config. Formatters.oftype<jsonmediatypeformatter> ().
A ();
JsonFormatter.SerializerSettings.ContractResolver = new Camelcasepropertynamescontractresolver (); Web API routes config.
Maphttpattributeroutes (); Config.
Routes.maphttproute (Name: "Defaultapi", Routetemplate: "Api/{controller}/{id}",
defaults:new {id = routeparameter.optional}); }
}
The Jsonformatter object is first obtained from the Httpconfiguration object, and then the Contractresolver property is set. Then it's "Camel" style when we use the JSON data format.
2. For returning a single resource, we should return the corresponding status code (for example: Success 200, resource not found 404, etc.), Solution: Httpresponsemessage Object
There is a "httpresponsemessage" class in the Web API framework that can be used to return an HTTP status code. Sometimes using the status code instead of model to respond to the client will be better
Public httpresponsemessage getcourse (int id)
{
try
{
var course = therepository.getcourse (ID);
if (course!= null)
{return
request.createresponse (Httpstatuscode.ok, Themodelfactory.create (course));
}
Else
{return
request.createresponse (httpstatuscode.notfound);
}
}
catch (Exception ex)
{return
request.createerrorresponse (Httpstatuscode.badrequest, ex);
}
}
Http://www.cnblogs.com/yxlblogs/p/3657602.html