Use of attributes in C#

Asked

Viewed 37 times

0

I am facing a situation where in a large part of the methods of my API I need to send a request for another API to account for calls and so invoice them.

Currently this code is contained in these methods, I wonder if it is possible to reduce this code to an attribute leaving the code more or less as below:

[Faturavel] // Atributo que rodará um código para enviar requisição para outra API
[HttpGet] 
[Route("Teste")]
public ActionResult Get() { return Ok(); }

This logic is possible?

Or is there another more appropriate way to implement this solution?

I tried to implement the billing attribute, but when the Get() method is called the http request is not sent.

[AttributeUsage(AttributeTargets.Method, Inherited = false)]
    public class Faturavel: Attribute
    {
        public Faturavel()
        {
            using HttpClient HttpClient = new();
            using HttpRequestMessage Request = new(HttpMethod.Post, new Uri("http://localhost:44326/teste/ok"));


            using HttpResponseMessage Response = HttpClient.Send(Request);

            if (Response.StatusCode != System.Net.HttpStatusCode.OK)
                throw new ApplicationException("Falha ao integrar!");
        }
    }

This way I would like when the Get() method is called, to execute the code that is in the Invoicing class, but this is not happening. When I run the project the class is being called 4x and when I do GET nothing happens.

  • it is not very clear your question... as it is a custom attribute it is possible to program whatever you want in it and put your logic there, so at first, without more details, I would say yes

  • Thanks for the answer Ricardo, I will edit the question trying to make clearer.

1 answer

0


What you can create is a Filterattribute

public class AutoLogAttribute : TypeFilterAttribute
{
    public AutoLogAttribute() : base(typeof(AutoLogActionFilterImpl))
    {

    }

    private class AutoLogActionFilterImpl : IActionFilter
    {
        private readonly ILogger _logger;
        public AutoLogActionFilterImpl(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<AutoLogAttribute>();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            // perform some business logic work
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
        }
    }
}

Then just use in your controller

[AutoLog]
public Task<IActionResult> QualquerMetodo()

You can also use an Authorizationfilter

public class ValidationFilter : AuthorizeFilter, IActionFilter
{
    public ValidationFilter()
    {
    }

    public ValidationFilter(AuthorizationPolicy policy) : base(policy)
    {
    }

    public override Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        return base.OnAuthorizationAsync(context);
    }
    public void OnActionExecuted(ActionExecutedContext context)
    {
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        
    }        
}

At Startup.Cs

public void ConfigureServices(IServiceCollection services)
    {            
        services.AddControllers(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                               .RequireAuthenticatedUser() // Ou remove se não precisa estar autenticado
                               .Build();
            config.Filters.Add(new ValidationFilter(policy));
        });
    }

Then just use the attribute [Authorize]

  • Thanks! It worked out!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.