Asp.net WebApi usage summary, asp. netwebapi
If you want the server to directly return json or xml, you can consider using webservice, wcf, or webapi. Webservice is based on xml, which is slow in efficiency. Although wcf can return json, the configuration is cumbersome. Compared with the previous two, webapi is simple, flexible, and efficient. It is the first choice for creating api interfaces on the asp.net platform.
Visual studio 2017 new. net framework web application. Select webapi as the template. The default template has completed most of the configurations for you. Run the program directly and access the default controller ValuesController in the browser. You can see the effect by running/api/values. The access route configuration file of webapi is located in the app_start folder, and the configuration method is slightly different from that of mvc routing.
If you want to change the xml format returned by default to json format, you can add the following in the Application_Start method of the global file:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
In this way, the returned data will be formatted as json instead of xml.
However, the serialization method is provided by the system. If you want to customize the serialization method, you can directly return the HttpResponseMessage class in the controller, but the HttpResponseMessage must be built by yourself.
[AcceptVerbs ("get", "post")] // configure the accepted request type. Public HttpResponseMessage Demo () {string jsonStr = JsonConvert. serializeObject (new {Id = 10, Name = "ka"}); HttpResponseMessage result = new HttpResponseMessage {Content = new StringContent (jsonStr, Encoding. getEncoding ("UTF-8"), "application/json")}; return result ;}
Access the Demo method to view the result.
Reference blog: https://www.cnblogs.com/elvinle/p/6252065.html