The practice of refit in ASP. NET Core

Source: Internet
Author: User
Objective


Reputation service call, has been not a fresh topic, after all came out for many years.



Let's talk about the simple practice of using one of these components in a recent project.



Part of the current project is to use refit this component, are used in conjunction with the httpclientfactory.



A brief introduction to Httpclientfactory can be found in the official documentation, as well as a look at the previous two more sketchy descriptions.



Also a brief introduction to the background, there are two main types of API interface:



The first class is registered in Eureka and can be requested through service discovery, where the new interface is.



The second class is the original interface, can not walk the service discovery, can only be called by direct connection request, here are some of the old interface.



In other words, to be compatible with both types of interfaces.



Because it is easy to discover with httpclientfactory Integration Services, a component--refit with Httpclientfactory is preferred.


What is refit


Refit is an automatic type-safe rest library, which is a. NET client implementation of the RESTful architecture,



It is based on attribute, which provides the data returned by the rest API into (Plain ordinary C # object, simple C # objects), POCO to JSON, network request (Post,get,put,delete, etc.) encapsulation, The internal encapsulation uses httpclient, which focuses on the encapsulation of the interface, the latter focuses on the efficiency of the network request, the two division of cooperation.



Our application requests the network through the refit, actually uses the refit interface layer encapsulates the request parameter, the Header, the URL and so on the information, afterwards by the httpclient completes the subsequent request operation, after the service side returns the data, httpclient the original result gives Refit, the latter is the process of parsing the results based on the user's needs.



For more details, refer to Refit's website.


Create a callable API interface


Directly on the controller's Code 〜〜


// GET: api/persons
[HttpGet]
public IEnumerable<Person> Get()
{
    return new List<Person>
    {
        new Person{Id = 1 , Name = "catcher wong", CreateTime = DateTime.Now},
        new Person{Id = 2 , Name = "james li", CreateTime = DateTime.Now.AddDays(-2)}
    };
}

// GET api/persons/5
[HttpGet("{id}")]
public Person Get(int id)
{
    return new Person { Id = id, Name = "name" };
}

// POST api/persons
[HttpPost]
public Person Post([FromBody]Person person)
{
    if (person == null) return new Person();

    return new Person { Id = person.Id, Name = person.Name };
}

// PUT api/persons/5
[HttpPut]
public string Put([FromBody]int id)
{
    return $"put {id}";
}

// DELETE api/persons/5
[HttpDelete("{id}")]
public string Delete(int id)
{
    return $"del {id}";
}
Use of Refit


Install the refit package through NuGet first.



And then it's the definition of our interface.


public interface IPersonsApi
{
    [Get("/api/persons")]
    Task<List<Person>> GetPersonsAsync();

    [Get("/api/persons/{id}")]
    Task<Person> GetPersonAsync([AliasAs("id")]int personId);

    [Post("/api/persons")]
    Task<Person> AddPersonAsync([Body]Person person);

    [Put("/api/persons")]
    Task<string> EditPersonAsync([Body]int id);

    [Delete("/api/persons/{id}")]
    Task<string> DeletePersonAsync(int id);
}


Take a look at some of the things that are involved in this interface.


    1. The Get,post feature indicates how the interface is requested, and the subsequent value is the relative path of the request.
    2. In a relative path, you can use placeholders to dynamically update parameter values.
    3. If the method name and request parameter names are inconsistent, you need to specify Aliasas.
    4. Declaring an object as a request body via the body attribute to the server
    5. The return value definition is a taskor iobservable


And then with the httpclientfactory.



And then install refit.httpclientfactory through NuGet.



If PERSONAPI is registered to Euerka, you can add the Steeltoe reference again.


public void ConfigureServices(IServiceCollection services)
{
    services.AddRefitClient<IPersonsApi>()
            .ConfigureHttpClient(options =>
            {
                options.BaseAddress = new Uri(Configuration.GetValue<string>("personapi_url"));
                //other settings of httpclient
            })
            //Steeltoe discovery
            //.AddHttpMessageHandler<DiscoveryHttpMessageHandler>()
            ;

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}


In the previous definition of the IPERSONAPI, we only specified the relative path, and the request IP is not specified, this is placed in the configurehttpclient inside to specify.



At the same time, according to different environment, configure different appsettings. {Env}.json, to achieve the effect of switching.



Similarly, if you want to go to service discovery, just let go of the comment addhttpmessagehandler, and modify the baseeaddress as the service name of the form can be.



Said so much, are still only the configuration phase, the following to see how the specific use.



For demonstration convenience, it is not built a service layer, directly in the controller call.



The usage is also very simple, directly in the controller to inject a bit can be used.


[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    private readonly IPersonsApi _api;
    public ValuesController(IPersonsApi api)
    {
        this._api = api;
    }

    // GET api/values
    [HttpGet]
    public async Task<List<Person>> GetAsync()
    {
        return await _api.GetPersonsAsync();                             
    }

    // GET api/values/5
    [HttpGet("{id}")]
    public async Task<Person> Get(int id)
    {
        return await _api.GetPersonAsync(id);
    }

    // POST api/values
    [HttpPost]
    public async Task<Person> Post([FromBody] Person value)
    {
        return await _api.AddPersonAsync(value);
    }
}


Here, the code-level stuff has been processed.



Here's a look at the use of the refit effect (see only two GET requests here):









are able to get the results we expect from normal.



Finally, look at the output of the log, confirm.



The first is/api/valuesthe access






Indeed, the request was made to the personapi in front of us.



Then it's/api/values/5555the access






It can be seen that the aliases above (Aliasas) are effective, to be able to spell the correct request address.



As for other types of requests, here is not a demonstration, let everyone try it yourself.


Summarize


Refit use up or relatively simple, run for some time also performance normal!



Of course, this article is only a few basic usage of the introduction! It also has a good extensibility that allows us to do something customized according to our own needs.



The sample code for this article Refitclientapi


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.