0

I created a custom attribute and I need to pass a value from route to this attribute, how can I do this?

public class MyAttribute : Attribute
{
    public MyAttribute(string myvalue)
    {
        // use myvalue...
    }
}

[MyAttribute]
[Route("/action/{myvalue}")]
public IActionResult Action(string myvalue)
{
   
}
mohammad
  • 339
  • 1
  • 3
  • 10
  • If you really mean this is an `asp.net core` question, you need `IHttpContextAccessor` instead of `HttpContextBase` which is really gone away in the world `asp.net core`. – King King Jan 26 '21 at 11:47

1 Answers1

2

you can inject HttpContextAccessor to your attribute class and then read the route parameters

public class MyAttribute : Attribute
{
    private readonly HttpContextAccessor _accessor;

    public MyAttribute(HttpContextAccessor accessor)
    {
        _accessor = accessor; 
        var myValue = _accessor.HttpContext.Request.RouteValues.GetValueOrDefault["myValue"];
        // ...
    }
}
Ali Faris
  • 17,754
  • 10
  • 45
  • 70
  • you knew really well about the OP's question when he tagged his question as `asp.net-core` but looks like it's actually for the old `asp.net`, because there is no `HttpContextBase` in `asp.net-core` https://stackoverflow.com/questions/44775390/httpcontextbase-namespace-could-not-be-found So the answer and the question both confuse the readers, really bad. At least you should've mentioned about that in your answer. – King King Jan 26 '21 at 11:46
  • also with the usage of this attribute by the OP `[MyAttribute]`, how could this be used at all? We have way to use it but really this answer does not talk about that and the OP (at his level of understanding) seems to automatically know how to use that attribute, what a genius. – King King Jan 26 '21 at 11:50
  • no actually logically, this is so strange. It's really like you and the OP are one person, ***really*** or at least there is some close relationship in real life. – King King Jan 26 '21 at 13:23
  • 1
    you're welcome. btw it's worth it because as I said it's confusing. Unless someone edits the question's tag to replace `asp.net-core` with `asp.net`. – King King Jan 26 '21 at 13:35
  • how can I use this attribute in my controller? – mohammad Jan 31 '21 at 09:06
  • checkout this https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0#attribute-routing-for-rest-apis – Ali Faris Jan 31 '21 at 09:13
  • @AliFaris in the controller i need to pass instead of HttpContextAccessor , how can i inject this to attribute? – mohammad Jan 31 '21 at 09:41
  • I'm sorry, I can't understand you – Ali Faris Jan 31 '21 at 10:26
  • @AliFaris I hope you will by checking this link https://stackoverflow.com/questions/65981258/dependency-injection-in-custom-attribute – mohammad Jan 31 '21 at 16:07