vendredi 22 janvier 2021

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?





Aucun commentaire:

Enregistrer un commentaire