Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create the Web API of ASP.NET Core

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of "how to create the Web API of ASP.NET Core". The editor shows you the operation process through the actual case, and the operation method is simple, fast and practical. I hope that this article "how to create the Web API of ASP.NET Core" can help you solve the problem.

1. A brief introduction

ASP.NET Core Web API is a function of ASP.NET Core MVC. ASP.NET Core MVC includes support for Web API. You can build a variety of client-side HTTP services. ASP.NET Core Web API can be used to build RESTful applications on the .NET Core.

The framework includes support for HTTP content negotiation and built-in support for data formatted in JSON or XML. Writing a custom formatter has added support for your own format.

Use links to generate support for hypermedia. Enable support for cross-resource sharing (CORS) so that Web API can be shared among multiple Web applications.

For example, create a new API project that contains a ValuesController by default:

[Route ("api/ [controller]")] [ApiController] public class ValuesController: ControllerBase {/ / GET api/values [HttpGet] public ActionResult Get () {return new string [] {"value1", "value2"} } / / GET api/values/5 [HttpGet ("{id}")] public ActionResult Get (int id) {return "value" } / / POST api/values [HttpPost] public void Post ([FromBody] string value) {} / / PUT api/values/5 [HttpPut ("{id}")] public void Put (int id [FromBody] string value) {} / / DELETE api/values/5 [HttpDelete ("{id}")] public void Delete (int id) {}}

The HTTP request operations of GET,POST,PUT,DELETE are included by default. Feature routing is used directly here, indicating [Route ("api/ [controller]")] on the controller. Debug and open a browser to enter https://localhost:5000/api/values, and data will be returned.

two。 Custom formatting (Format)

ASP.NET Core MVC built-in support for the format of the corresponding data, used to modify the format or generate the format specified by the client.

1. Results of operations in a specific format

The type of result of some operations is in a specific format, such as JsonResult or ContentResult. The operation can always return specific results in a specific format. For example, JSON formatting data will be returned when JsonResult is returned, regardless of the format required by the client.

The operation does not require any specific type to be returned, and MVC supports any object as the return value. If the operation returns an implementation of IActionResult and the controller inherits from Controller, more helper methods can be used. If not, the object will be serialized using the appropriate IOutputFormatter implementation.

To return data in a specific format from a controller that inherits the Controller base class, you can use the built-in helper method Json to return JSON format and Content to return plain text. The return type of the action method must be the specified result type (such as JsonResult) or IActionResult.

[HttpGet] public JsonResult Get () {return Json (new User ());

The above code Content-Type will return application/json.

To return data in plain text format, use the ContentResult and Content helper methods:

[HttpGet] public ContentResult Get () {return Content ("result");}

The above code Content-Type will return test/plan. You can also use a string corresponding type to implement this behavior:

[HttpGet] public string Get () {return "result";}

For complex operations with multiple return types or options, select IActionResult as the return type.

two。 Configure the formatter

If your application wants to support formats other than the default JSON, you can add these additional dependencies to the project.json file and configure MVC to support it. The format of input and output can be isolated. The input format is bound using the model, and the output format is formatted in response.

3. Add support for XML format

To add support for XML format, you need to install the Microsoft.AspNetCore.Mvc.Formatters.Xml package first, and then configure XmlSerializerFormatters in ConfigureServices:

Services.AddMvc () .AddXmlSerializerForbidden () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1)

Or you can just add the output format:

Services.AddMvc (options = > {options.OutputFormatters.Add (new XmlSerializerOutputFormatter ());}) / / .AddXmlSerializerForbidden () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1)

Both methods will use System.Xml.Serialization.XmlSerializer to serialize the results. You can also use System.Runtime.Serialization.DataContractSerializer by adding other related formats:

Services.AddMvc (options = > {options.OutputFormatters.Add (new XmlDataContractSerializerOutputFormatter ());}) / / .AddXmlSerializerForbidden () .SetCompatibilityVersion (CompatibilityVersion.Version_2_1); 4. Force specific formatting

If you want to restrict the response format for an operation, you can use the [Produces] filter. The [Produces] filter can specify the response format for this controller or Action:

[HttpGet ("{id}", Name = "Get")] [Produces ("application/json")] public string Get (int id) {return "value";}

For some special cases, you may not want to use a built-in formatting implementation. By default, when the return type is string, it is formatted as text/plain. This behavior can be changed by removing TextOutputFormatter:

Public void ConfigureServices (IServiceCollection services) {services.AddMvc (options = > {options.OutputFormatters.RemoveType (); options.OutputFormatters.RemoveType ();}) .SetCompatibilityVersion (CompatibilityVersion.Version_2_1);}

TextOutputFormatter and HttpNoContentOutputFormatter are removed above, and 406 Not Acceptable is returned when the return type is string. If an XML formatter exists, the response result is formatted.

When HttpNoContentOutputFormatter is removed, a 204NoContent response is returned when an operation with a return type of model object returns null. The JSON format will simply return the response whose body information is null, while the XML format will return an empty XML element with the xsi:nil= "true" attribute.

5. Response format URL mapping

The client can request a specific format in URL, such as in the request string or path, or by using a specific format file extension (such as .xml or .json), which needs to be specified in the route used by API:

[FormatFilter] public class UserController: Controller {/ / GET: api/User [HttpGet] [Route ("[controller] / [action] / {id}. {format?}")] public IActionResult GetById (int id) {return Content ("xxx");}}

This routing configuration will allow you to specify the format using an optional file extension. The [FormatFilter] attribute checks in RouteData whether the value of this format exists and maps the response data to the appropriate format when the response is created:

RouteFormatter

/ User/GetById/5: default output format

/ User/GetById/5.json: JSON format (if configured)

/ User/GetById/5.xml;: XML format (if configured)

6. Custom formatter Protocol Buffers (protobuf for short)

Protocol Buffers is a lightweight and efficient structured data storage format that can be used for structured data serialization, or serialization. It is suitable for data storage or RPC (remote procedure call Protocol) data exchange format. Can be used for communication protocols, data storage and other fields of language-independent, platform-independent, extensible serialized structural data format. For example, to implement a program to return protobuf format:

Create an API project and add a protobuf-net reference.

Add the ProtobufFormatter class:

Public class ProtobufFormatter:OutputFormatter {public string ContentType {get; private set;} public ProtobufFormatter () {ContentType = "application/proto"; SupportedMediaTypes.Add (MediaTypeHeaderValue.Parse ("application/proto"));} public override Task WriteResponseBodyAsync (OutputFormatterWriteContext context) {if (context = = null) {throw new ArgumentNullException (nameof (context)) } var response = context.HttpContext.Response; Serializer.Serialize (response.Body,context.Object); return Task.FromResult (0);}}

Inherit OutputFormatter, then implement the WriteResponseBodyAsync method, assign ContentType on initialization, and add support MediaType. Get the Response in the WriteResponseBodyAsync method, and call the Serializer.Serialize method of protobuf-net to serialize the Object to the output. Protobuf must specify the order when serializing, add the User class, and implement the protobuf entity:

[ProtoContract] public class User {[ProtoMember (1)] public int Id {get; set;} [ProtoMember (2)] public string Name {get; set;} [ProtoMember (3)] public int Age {get; set;}}

The [ProtoContract] attribute needs to be added on the class, the ProtoMember attribute is required on the field, and the order is specified. Then modify the UserController:

[Route ("api/ [controller]")] [ApiController] [FormatFilter] public class UserController: Controller {private IEnumerable users; public UserController () {users = new User [] {new User () {Id=1,Name= "Bob", Age = 20}, new User () {Id=2,Name= "Tom", Age = 22}} } / GET: api/User [HttpGet] [Produces ("application/proto")] public IEnumerable Get () {return users;}}

Modify ConfigureServices:

Public void ConfigureServices (IServiceCollection services) {services.AddMvc (options = > {options.OutputFormatters.Add (new ProtobufFormatter ());}) .SetCompatibilityVersion (CompatibilityVersion.Version_2_1);}

Running the program returns a binary file.

Create a console and check the serialization:

Class Program {static void Main (string [] args) {HttpClient client = new HttpClient (); var stream = client.GetStreamAsync ("https://localhost:44358/api/User").Result; var users = Serializer.Deserialize (stream)) Foreach (var user in users) {Console.WriteLine ($"Id: {user.Id}-Name: {user.Name}-Age: {user.Age}");} Console.ReadKey ();}} that's all about "how to create the Web API of ASP.NET Core". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report