WebApi, webapi

Source: Internet
Author: User

WebApi, webapi

Formatting data mainly depends on the applicable scenarios. Today we will share with you how to format data through webapi. The example below mainly refers to the output of json and xml format data, the test cases are very similar to common cases. I hope you will like them, and I hope you can scan more code to support and like them. Thank you:

 

. Customize an Action to respond to the output set data

The api returns json data in two ways.

. Json time format processing method

. Enable the api to support returning json and xml data

 

Let's share it one step at a time:

. Customize an Action to respond to the output set data

First, we create a new webapi project. After the new project is created, we can find Controllers/ValuesController. check the cs file to see the automatically generated code. Let's skip it first. Then we create a student MoStudent class. The property code is as follows:

 1 public class MoStudent 2     { 3         public DateTime Birthday { get; set; } 4  5         public int Id { get; set; } 6  7         public string Name { get; set; } 8  9         public bool Sex { get; set; }11     }

Then, we initialize some public data in ValuesController. The Code is as follows:

1 public List <MoStudent> students = new List <MoStudent> () {2 3 new MoStudent {Id = 1, Name = "small 1", Sex = true, Birthday = Convert. toDateTime ("1991-05-31")}, 4 new MoStudent {Id = 2, Name = "2", Sex = false, Birthday = Convert. toDateTime ("1991-05-31")}, 5 new MoStudent {Id = 3, Name = "small 3", Sex = false, Birthday = Convert. toDateTime ("1991-05-31")}, 6 new MoStudent {Id = 4, Name = "Small 4", Sex = true, Birthday = Convert. toDateTime ("1991-05-31")} 7 };

Then, we create a new GetAllStudents01 () method and output the student set data. The Code is as follows:

1  public List<MoStudent> GetAllStudents01()2         {3             return students;4         }

At this time, we will generate a project and access the address http: // localhost: 1001/api/values in the browser. An error message will be prompted:

The error message is that the address matches the Action of two APIs at the same time, namely Get () and GetAllStudents01 (). How should we handle this error; one method can be used to delete one of the two methods is to set the Action under the default route, and then access it through the specific Controller/Action address.RouteModify the corresponding access route (as described in the previous article). Here we use the second method. Modify WebApiConfig first. the default route configuration in the cs file. The modified configuration is as follows:

1 config.Routes.MapHttpRoute(2                 name: "DefaultApi",3                 routeTemplate: "api/{controller}/{action}/{id}",4                 defaults: new { id = RouteParameter.Optional }5             );

After the code is generated, we access http: // localhost: 1001/api/values/GetAllStudents01 in the browser. GetAllStudents01 is the name of the Action to be accessed, we can see the following results in the browser:

Webapi can return data normally, but the address looks like a long one, which is not conducive to our test. So next we will use the mark used in the previous articleRoutePrefixAndRouteTo change the route. The added code is as follows:

Then we will test whether the above data can be returned normally at the address http: // localhost: 1001/s/all01;

 

The api returns json data in two ways.

First, let's look back at the node example above. The interface response outputs data in xml format. Here, the xml format provided by webapi is used by default, show all the Student attributes. When we actually Develop interfaces, some object attributes are usually not displayed, next we will add DataContract and DataMember to set to "hide" the attributes that do not need to be exposed. Let's first look at the added Student Entity after the two tags:

 1 [DataContract] 2     public class MoStudent 3     { 4         [DataMember] 5         public DateTime Birthday { get; set; } 6  7         [DataMember] 8         public int Id { get; set; } 9 10         [DataMember]11         public string Name { get; set; }12 13         [DataMember]14         public bool Sex { get; set; }15 16     }

Then run the program. The result information displayed on the page is exactly the same as the previous result:

Remove the DataMember above the Birthday attribute and run the following command to view the result:

We can see that the Birthday is no longer displayed in the output result. The result shown here is that if DataMember is not marked, it will not be output. Let's look at something useful, let's reply to the Birthday DataMember and modify it to the following code:

 1 [DataContract] 2     public class MoStudent 3     { 4         [DataMember(Order = 3)] 5         public DateTime Birthday { get; set; } 6  7         [DataMember(Order = 0)] 8         public int Id { get; set; } 9 10         [DataMember(Order = 1)]11         public string Name { get; set; }12 13         [DataMember(Order = 2)]14         public bool Sex { get; set; }15 16     }

Then let's run it again and see:

I believe that careful friends can find that the temporary location of the Birthday data has changed from the first data to the last one. Yes, this is the effect of the Order attribute parameter in DataMember: specifies the position where output data is displayed;

Let's take a look at the question. Here we will explain two types of json data returned by webapi. One is to use the built-in Json format method. asax. clear the default xml output method in the cs file. The Code is as follows:

1 var format = GlobalConfiguration. Configuration. Formatters; 2 // Clear the default xml3 format. XmlFormatter. SupportedMediaTypes. Clear ();

When webapi is started, xml and json data are formatted by default. xml is the default start method. Therefore, xml format must be cleared, then there is only json left, so we can see the result output after running the program:

Json data is returned. If we want to hide Birthday like the xml above, we can also use DataContract and DataMember To Do This. After deleting the DataMember mark corresponding to Birthday, we can see the following results:

Similarly, we restore the DataMember of Birthday and specify the Order attribute value [DataMember (Order = 1)]. In this way, the position displayed on Birthday changes:

Let's try the first json format method. The following describes how to use Json. to avoid affecting the effect, we put Global. asax. restore the cs file and add an Action method again. The Code is as follows:

 1 [Route("all01_1")] 2         public async Task<HttpResponseMessage> GetAllStudents01_1() 3         { 4             var result = await JsonConvert.SerializeObjectAsync(students); 5  6             return new HttpResponseMessage 7             { 8                 Content = new StringContent(result), 9                 StatusCode = HttpStatusCode.OK10             };11         }

Json is used here.. Net JsonConvert. the SerializeObjectAsync method is used to format a string and then pass it to HttpResponseMessage. The final output result is the same as above. Well, let's take a look at how this method hides attributes that do not require interface exposure, here we use the JsonIgnore mark. The test case is modified in the object class as follows:

1 [JsonIgnore]2 public DateTime Birthday { get; set; }

Run the command to check the effect:

Let's take a look at how to set the attribute sorting. You can use JsonProperty (Order = 1). The Code for modifying the object class is as follows:

 1 public class MoStudent 2     { 3         //[DataMember(Order = 1)] 4         [JsonProperty(Order = 1)] 5         public DateTime Birthday { get; set; } 6  7         //[DataMember(Order = 0)] 8         [JsonProperty(Order = 0)] 9         public int Id { get; set; }10 11         //[DataMember(Order = 1)]12         [JsonProperty(Order = 1)]13         public string Name { get; set; }14 15         //[DataMember(Order = 2)]16         [JsonProperty(Order = 2)]17         public bool Sex { get; set; }18 19     }

The result is the same as that set for DataMember:

 

. Json time format processing method

For time formatting, the usual birthday format is yyyy-MM-dd. We will also format the time converted from the preceding two json formats. Let's take a look.Json.netFirst, we define a class named SelfDateTimeFormat and inherit the DateTimeConverterBase class. Then we need to rewrite ReadJson and WriteJson. The following describes all the methods of this class:

1 /// <summary> 2 /// custom time formatting 3 /// </summary> 4 public class SelfDateTimeFormat: DateTimeConverterBase 5 {6 public IsoDateTimeConverter TimeConvert = null; 7 8 public SelfDateTimeFormat () {9 10 TimeConvert = new IsoDateTimeConverter11 {12 DateTimeFormat = "yyyy-MM-dd" 13 }; 14} 15 16 public SelfDateTimeFormat (string formatter = "yyyy-MM-dd HH: mm: ss") 17 {18 19 TimeConvert = new IsoDateTimeConverter20 {21 DateTimeFormat = formatter22 }; 23} 24 25 public override object ReadJson (Newtonsoft. json. jsonReader reader, Type objectType, object existingValue, Newtonsoft. json. jsonSerializer serializer) 26 {27 28 return TimeConvert. readJson (reader, objectType, existingValue, serializer); 29} 30 31 public override void WriteJson (Newtonsoft. json. jsonWriter writer, object value, Newtonsoft. json. jsonSerializer serializer) 32 {33 34 TimeConvert. writeJson (writer, value, serializer); 35} 36}

Then we need to add the following mark on the time attribute of the object class: [JsonConverter (typeof (OverridClass. selfDateTimeFormat)]. Here, SelfDateTimeFormat is the custom formatting time class we just defined. Let's take a look at the output result data:

Well, let's take a look at how to define a date format data in json format provided by webapi. We need to add the following code in Global. asax. cs:

1 var format = GlobalConfiguration.Configuration.Formatters;2             format.JsonFormatter.SerializerSettings.DateFormatString = "yyyy.MM.dd";

Yes, you only need such simple code to format the time:

 

. Enable the api to support returning json and xml data

In the first section, webapi has its own json and xml formatting. Here we will set different data formats to be returned through parameter requests. First, we need to set the following code in Global:

1 var format = GlobalConfiguration. configuration. formatters; 2 format. jsonFormatter. serializerSettings. dateFormatString = "yyyy. MM. dd "; 3 4 // clear the default xml5 format. xmlFormatter. supportedMediaTypes. clear (); 6 7 // return format 8 format through parameter settings. jsonFormatter. mediaTypeMappings. add (new QueryStringMapping ("t", "json", "application/json"); 9 format. xmlFormatter. mediaTypeMappings. add (new QueryStringMapping ("t", "xml", "application/xml "));

The QueryStringMapping class is used here, and the new QueryStringMapping ("t", "json", "application/json") and new QueryStringMapping ("t ", "xml", "application/xml"), json and xml are used respectively, and the previous "t" indicates the parameter name t in the request url address, next we will test the parameters of the two types of requests, respectively:

Http: // localhost: 1001/s/all01? T = xml

 

Http: // localhost: 1001/s/all01? T = json

 

Now, I will share with you the content in this article. I personally feel that this example is very close to the actual usage. If you want to give me a thumbs up, thank you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.