5.3Defining Request Methods
In the IHttpService declarative interface, you can define various API request methods. These methods must be marked with attributes derived from HttpMethodAttribute to indicate their corresponding HTTP request type. The system provides a variety of common HTTP request method attributes out of the box, while also supporting custom method attributes:
public interface IHttpService : IHttpDeclarative{ // Define an HTTP GET request [Get("https://furion.net/")] Task<string> GetMethodAsync(); // Define an HTTP PUT request [Put("https://furion.net/")] Task<string> PutMethodAsync(); // Define an HTTP POST request [Post("https://furion.net/")] Task<string> PostMethodAsync(); // Define an HTTP DELETE request [Delete("https://furion.net/")] Task<string> DeleteMethodAsync(); // Define an HTTP HEAD request [Head("https://furion.net/")] Task<string> HeadMethodAsync(); // Define an HTTP OPTIONS request [Options("https://furion.net/")] Task<string> OptionsMethodAsync(); // Define an HTTP TRACE request [Trace("https://furion.net/")] Task<string> TraceMethodAsync(); // Define an HTTP PATCH request [Patch("https://furion.net/")] Task<string> PatchMethodAsync(); // Define an HTTP QUERY request [Query("https://furion.net/")] Task<string> PatchMethodAsync(); // Custom HTTP request method [HttpMethod("Connect", "https://furion.net/")] Task<string> ConnectMethodAsync(); // Define a generic method [Get("https://furion.net/")] Task<T> GenericMethodAsync<T>();}public interface IHttpService : IHttpDeclarative{ // Missing the [HttpMethod] attribute, which will cause an exception Task<string> UnknownMethodAsync();}Custom Request Methods
In addition to directly using [HttpMethod("Connect", "https://furion.net/")] to add a custom HTTP request method, we can also create a concrete ConnectAttribute attribute class to improve code reusability and readability. This attribute class inherits from HttpMethodAttribute and is specifically used to represent Connect requests.
[AttributeUsage(AttributeTargets.Method)]public sealed class ConnectAttribute : HttpMethodAttribute{ public ConnectAttribute(string? requestUri = null) : base("Connect", requestUri) { }}Now we can use the custom [Connect] attribute in the IHttpService interface to replace the previous [HttpMethod("Connect", ...)] attribute:
public interface IHttpService : IHttpDeclarative{ // Use the custom Connect attribute [Connect("https://furion.net/")] Task<string> ConnectMethodAsync();}Such code is more concise and clear, while also improving the maintainability and reusability of the code.