Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
113 views
in Technique[技术] by (71.8m points)

c# - Applying NonAction to controller method according to implemented interfaces

Here is my synchronisation controller, it allows to push and/or pull data.

public class SyncController : MyController
{
  ISyncable _sync;

  public SyncController(ISyncable sync) { _sync = sync; }

  [HttpPost, PullAction]
  public async Task<IActionResult> pull()
  {
    (_sync as IPullable).Pull();
  }

  [HttpPost, PushAction]
  public async Task<IActionResult> push()
  {
    (_sync as IPushable).Push();
  }
}

If ISyncable implements IPushable, controller shall provide the push method`.

If ISyncable implements IPullable, controller shall provide the pull method`.

So I'd like to apply [NonAction] attribute according to implemented interfaces.

I intend to do it with custom attributes:

[AttributeUsage(validOn: AttributeTargets.Method, AllowMultiple = false)]
public class PushActionAttribute : Attribute
{
    public PushActionAttribute([CallerMemberName] string propertyName = null)
    {
        Type syncType = ???;  // TODO get ISyncable type from propertyName
        bool isPushable = typeof(IPushable).IsAssignableFrom(syncType);

        if(!isPushable)
        {
          // TODO apply NonActionAttribute
        }
    }
}


[AttributeUsage(validOn: AttributeTargets.Method, AllowMultiple = false)]
public class PullActionAttribute : Attribute
{
    public PullActionAttribute([CallerMemberName] string propertyName = null)
    {
        Type syncType = ???;  // TODO get ISyncable type from propertyName
        bool isPullable = typeof(IPullable).IsAssignableFrom(syncType);

        if(!isPullable)
        {
          // TODO apply NonActionAttribute
        }
    }
}

Is it possible to retrieve syncType from attribute target?

Is it possible to apply [NonAction] attribute dynamically?

Is there a better way to implement this functionality?

question from:https://stackoverflow.com/questions/65844221/applying-nonaction-to-controller-method-according-to-implemented-interfaces

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Can you simply do:

if (_sync is IPullable) (_sync as IPullable).Pull();

? No added complexity of reflection, attributes and other boilerplate. I don't think there is a dynamic/runtime way of adding attributes of disabling methods.

You could return NotFound if it fails, e.g.

[HttpPost]
public IActionResult push()
{
    if (_sync is IPushable) (_sync as IPushable).Push();
    else return NotFound();
    return View();
}

(removed async Task, as there's no await or returned Task)...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...