C# 限制对方法的访问

C# 限制对方法的访问,c#,.net-core,C#,.net Core,我已经创建了一个自定义属性,您可以使用它来装饰控制器中的方法 我的服务层中还有一个方法,只能从与我的属性解除等级的控制器方法访问该方法。这可能吗 范例 [MyCustomAttribute] [HttpGet] public IEnumerable<WeatherForecast> Get() { // Should be allowed to call the method below _service.GetWeatherInfo(); } [HttpGet]

我已经创建了一个自定义属性,您可以使用它来装饰控制器中的方法

我的服务层中还有一个方法,只能从与我的属性解除等级的控制器方法访问该方法。这可能吗

范例

[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
}
[MyCustomAttribute]
[HttpGet]
公共IEnumerable Get()
{
//应该允许调用下面的方法
_service.GetWeatherInfo();
}
[HttpGet]
公共IEnumerable Get()
{
//不应允许调用下面的方法
_service.GetWeatherInfo();//此处不应访问此项
}

如果你真的想做这样的事情,你可以尝试下面的方法,尽管这不是很好,因为它目前只适用于一个控制器。如果您没有使用ASP的经验,我会说查看属性,然后仅从使用特定策略修饰的操作调用您的服务方法

public void GetWeatherInfo([CallerMemberName] string methodName = null)
{
    var hasAttribute = typeof(WeatherController).GetMethod(methodName).GetCustomAttributes(typeof(MyCustomAttribute), true).Any();

    if(!hasAttribute)
         throw new Exception("Forbidden");
}

不是用C#as,不是。你可以用Roslyn分析器执行类似的操作。你可以加载堆栈跟踪,然后查看哪个函数调用了你的函数,并通过反射检查它是否具有该属性。但这将在运行时检查,而不是在编译时检查。虽然您可以使用Roslyn分析器来强制执行此操作,但它似乎有点极端。你为什么认为首先限制这种方法是个好主意?@DavidG:这只是我的想法。但我会找到另一个解决方案。:)这假设它只来自一个控制器,因此该属性本质上是无意义的。它也违反了实体原则。服务不应该知道控制器。对不起,我得投反对票。