使用扩展方法重构控制器
我一直在关注此视频,在第40分钟,他们建议使用扩展方法在控制器操作中清理可重复的代码:
https://www.youtube.com/watch?v=h7tj7eget7eg7q&; t = 693s
我有每个控制器中重复的代码:
var currentUserId = HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return NotFound();
}
执行此不同的逻辑后,执行了另一种逻辑而且它总是返回状态代码确定。
我一直在尝试以扩展方法提取它:
public static IActionResult NotFoundOnEmptyUserId(this ControllerBase controllerBase)
{
var currentUserId = controllerBase.HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return controllerBase.NotFound();
}
}
但是,我不知道该如何返回确定,因为每个端点的逻辑都不同。
例如,postearsearchfilter是这样:
var filter = await _agentService.SaveFilterByUserId(currentUserId.Value, request.FilterName, request.SearchFiltersToSaveJson, ipAddress);
return this.Ok(filter);
删除搜索过滤器是:
await _agentService.DeleteUserSearchFilter(currentUserId.Value, filterId, ipAddress);
return this.Ok();
它们显然取决于此CurrentUserId。有什么建议吗?
I have been following this video and at minute 40 they suggest using extension method to clean up repeatable code in controller actions:
https://www.youtube.com/watch?v=h7TJ7eGeT7Q&t=693s
I have this piece of code which repeats in every Controller:
var currentUserId = HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return NotFound();
}
After this is executed a different logic is executed and it always returns status code Ok.
I have been trying to extract this in an Extension Method:
public static IActionResult NotFoundOnEmptyUserId(this ControllerBase controllerBase)
{
var currentUserId = controllerBase.HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return controllerBase.NotFound();
}
}
However, I do not know what to do with returning OK as the logic is different for every endpoint.
For example PostSearchFilter is this:
var filter = await _agentService.SaveFilterByUserId(currentUserId.Value, request.FilterName, request.SearchFiltersToSaveJson, ipAddress);
return this.Ok(filter);
and delete search filter is :
await _agentService.DeleteUserSearchFilter(currentUserId.Value, filterId, ipAddress);
return this.Ok();
They obviously depend on this currentUserId. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最好将中间件用于此目的。这样的事情:
It's better to use middleware for this purpose. Something like this: