我有两个基类RequestBase
和ResponseBase
, 分别用于请求和响应。从这些类派生的所有类型的请求和响应。RequestBase
包含ClientKey
和AccessToken
字段。另外,我有AuthenticationService
服务。
[ServiceContract]
public interface IAuthenticationService
{
[OperationContract]
public LoginResponse Login(LoginRequest request);
... other methods
}
假设我们有OrderService
服务。
public class OrderService:IOrderService
{
public OrderResponse GetOrders(OrderRequest request)
{
...
}
}
我需要验证 and 的每个请求ClientKey
,AccessToken
还要检查用户是否经过身份验证。我可以执行以下操作:
public OrderResponse GetOrders(OrderRequest request)
{
var response = new OrderResponse(request.RequestId);
// call helper method for validation
var validationResult = ValidateRequest.Validate(request, response, ValidateOptions.All)
...
}
但是我不想在每个方法中都写这行代码:
var validationResult = Validate.ValidRequest(request, response, ValidateOptions.All)
做这个的最好方式是什么?
PS。这是Validate
方法:
public static bool Validate(RequestBase request, ResponseBase response, ValidateOptions validate)
{
//Validate Client Key.
// Hardcoded here.
if ((Validate.ClientKey & validate) == Validate.ClientKey)
{
if (request.ClientKey != "ABC123")
{
response.Acknowledge = AcknowledgeType.Failure;
response.Message = "Unknown Client Key";
return false;
}
}
// Validate access token
if ((Validate.AccessToken & validate) == Validate.AccessToken)
{
if (request.AccessToken != _accessToken)
{
response.Acknowledge = AcknowledgeType.Failure;
response.Message = "Invalid or expired AccessToken. Call GetToken()";
return false;
}
}
// Validate user credentials
if ((Validate.UserCredentials & validate) == Validate.UserCredentials)
{
if (_userName == null)
{
response.Acknowledge = AcknowledgeType.Failure;
response.Message = "Please login and provide user credentials before accessing these methods.";
return false;
}
}
return true;
}
还有一个问题:服务器上最好的存储位置在_accessToken
哪里_userName
?