Consent 代码重构

学习分享 丨作者 / 郑 子 铭 丨公众号 / DotNet NB / CloudNative NB

任务23:Consent 代码重构

新建一个 Sercices 文件夹,在文件夹下新建一个 ConsentService,专门用于处理 Consent 的逻辑,我们会把 controller 中不是 action 的方法移到 service 中

先将 ConsentController 私有变量和构造函数搬到 ConsentService 中

ConsentService

private readonly IClientStore _clientSotre;
private readonly IResourceStore _resourceStore;
private readonly IIdentityServerInteractionService _identityServerInteractionService;

public ConsentService(
    IClientStore clientStore,
    IResourceStore resourceStore,
    IIdentityServerInteractionService identityServerInteractionService)
{
    _clientSotre = clientStore;
    _resourceStore = resourceStore;
    _identityServerInteractionService = identityServerInteractionService;
}

接着搬移私有方法,并将 BuildConsentViewModel 修改为 public

ConsentService

接着将 ConsentService 注入到 ConsentController 中并调用 BuildConsentViewModel

ConsentController

接着将 ConsentController 中 post 的逻辑搬到 ConsentService 的一个方法 ProcessConsent 中

这里不能直接调用 Redirect 所以需要一个新建一个ViewModel 作为返回

ProcessConsentResult

ConsentService

接着在 ConsentController 的 post 逻辑中调用 ProcessConsent

ConsentController

因为在视图层 index 中使用的是 ConsentViewModel,不能直接把 InputConsentViewModel 传过去,因为是无法识别的,所以我们需要在 ConsentService 中转换一下

首先在 ProcessConsentResult 中添加一个 ConsentViewModel

ProcessConsentResult

在什么情况下会返回这个 ViewModel,当 ConsentService 的 ProcessConsent 方法中的 consentResponse 为 null 的时候,在这个时候我们需要给它封装一个 model

ConsentService

但是在 BuildConsentViewModel 的时候,ConsentViewModel 的 ScopeViewModel 里面有 Required 和 Checked,如果在填写的时候已经勾选了,我们需要把它的状态带过去,而在 viewModel.ScopesConsented 的时候已经知道勾选了哪些,所以我们需要把 model 传过去

ConsentService

改造一下 BuildConsentViewModel,接收一个 InputConsentViewModel,默认为 null,如有它有值,可以知道客户的选中信息,然后传入 CreateConsentViewModel 中

ConsentService

所以在 CreateConsentViewModel 的时候对 Checked 赋值,或者已经选中的情况下就选中

ConsentService

接着处理一下 CreateConsentViewModel,传入一个 InputConsentViewModel,然后修改 RememberConsent,以及获取一个 selectedScopes

ConsentService

这一块就改进完了,接下来就是在不选中的情况下会有提示让我们选择,现在添加一些错误的提示,在 ProcessConsentResult 中添加一些信息

ProcessConsentResult

赋值 ValidationError

ConsentService

接着处理一下页面,将信息返回

ConsentController

加入验证信息之后需要修改视图把这块信息显示出来

Index

添加依赖注入

startup

启动服务端,启动客户端

因为默认勾选第一个,无法看到错误信息,所以去掉 disabled 与 hidden 控件,两个选项都不勾选,点击同意就会看到错误信息

_ScopeListitem

Last updated