将不同类的单个对象传递给单个方法,然后检查其类型

时间:2018-06-10 13:46:54

标签: c# api

不同的Models类有两到三个常见属性,如令牌字符串和卡号,它们在Controllers Api中的AuthenticateToken方法中使用。

我可以将单个泛型类型对象传递给AuthenticateToken并检查其中的对象类型,而不是在所有服务响应方法中传递卡和令牌字符串。将来,如果需要添加其他属性进行身份验证,则可以在AuthenticateToken中完成,并且不必更新所有服务响应方法。是否需要这样做?

[HttpPost]
public ServiceResponse GetBalance(ServiceInput serviceInput)
{
   if (AuthenticateToken(serviceInput.Token, serviceInput.CardNumber))
   {
      //do something;
   }
}

[HttpPost]
public ServiceResponse CancelVoucher(InvoiceInput serviceInput)
{
   if (AuthenticateToken(serviceInput.Token, serviceInput.CardNumber))
   {
      //do something;
   }
}

[HttpPost]
public ServiceResponse AddFunds(TransferInput serviceInput)
{
   if (AuthenticateToken(serviceInput.Token, serviceInput.CardNumber))
   {
      //do something;
   }
}

 private bool AuthenticateToken(string tokenString, string cardNumber)
    {
       return (token.AuthenticateToken(tokenString, cardNumber));
    }

我的想法

  private bool AuthenticateToken(object _obj)
    {
        var a;

        if (_obj is ServiceInput)
        {
           ServiceInput a = _obj as ServiceInput;
            //...
        }
        else if (_obj is InvoiceInput)
        {
           InvoiceInput a = _obj as InvoiceInput;
            //...
        }
        return (_token.AuthenticateToken(a.tokenString, a.cardNumber));

    }

0 个答案:

没有答案