Reputation: 3541
I have made a custom-attribute that you can use to decorate your methods in your Controller.
I also have a method in my service-layer that only should be accessed from controller method that are decoraded with my attribute. Is this possible to do?
Example
[MyCustomAttribute]
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
// Should be allowed to call the method below
_service.GetWeatherInfo();
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
// Should NOT be allowed to call the method below
_service.GetWeatherInfo(); // This should not be accessible here
}
Upvotes: 0
Views: 112
Reputation: 4839
If you really wanted to do something like that you could try the below, though it's not very good because it only works with one controller at the moment. If you have no experience with ASP I would say to look at the Authorize attribute and then only call your service method from actions decorated with a certain policy.
public void GetWeatherInfo([CallerMemberName] string methodName = null)
{
var hasAttribute = typeof(WeatherController).GetMethod(methodName).GetCustomAttributes(typeof(MyCustomAttribute), true).Any();
if(!hasAttribute)
throw new Exception("Forbidden");
}
Upvotes: 1