How to make a Custom Attribute in a webapi get the parameter passed via C#URL

Asked

Viewed 96 times

1

I am creating a Custom Attribute in a webapi to validate a value and I would like to know if you can capture this value from a GET request.

I wanted to do it that way:

[Validacao]
public Empresa consularEmpresa([FromUri]string codigo){}

Without having to pass it:

[Validacao("codigo")]
public Empresa consultaEpresa([FromUri]string codigo){}

Validation Code:

  [AttributeUsage(AttributeTargets.All)]
public class NfeValidation:ValidationAttribute
{
    public Validacao(string chave)
    {
        if (!string.IsNullOrEmpty(chave) && chave.Length == 44)
        {
            string modeloNF = chave.Substring(18,2);
            if(modeloNF != "55")
            {
                new HttpException("Modelo de nota fiscal inválido!");
            }
        }
    }
}

That up there is my example context of what I wanted to do.

For example, I need to validate an access key passed in my webapi via url and check if it is 44 digits and if the model is 55 plus first my (Attribute or Validationattribute) should validate this rule before executing my method

  • How is the code of Validacao ?

1 answer

1

I was able to solve it this way:

    public class ValidationNF:ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        base.OnActionExecuting(actionContext);
        var descriptor = actionContext.ControllerContext.ControllerDescriptor.ControllerName
                            + " - " + actionContext.ActionDescriptor.ActionName;

        var header = actionContext.Request.Headers;
        string erro = "";

}}

And I can take the data and validate it before I call the method. The call got that way exactly what I wanted:

    [ValidationNF]
public class ConsultaNFController : ApiController
{
    [AcceptVerbs("GET")]
    public Empresa ConsultaNfe([FromUri]string chave)
    {
        Empresa empresa = new Empresa();
        return empresa;
    }
}

Now I’ll treat what I need, thanks anyway;)

  • That’s right. It’s a good approach

Browser other questions tagged

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