使用扩展方法重构控制器
Refactor Controller using Extension method
我一直在关注这个视频,在第 40 分钟,他们建议使用扩展方法来清理控制器操作中的可重复代码:
https://www.youtube.com/watch?v=h7TJ7eGeT7Q&t=693s
我有这段代码在每个控制器中重复:
var currentUserId = HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return NotFound();
}
执行完后会执行不同的逻辑,它总是 returns 状态码 Ok。
我一直在尝试用扩展方法提取它:
public static IActionResult NotFoundOnEmptyUserId(this ControllerBase controllerBase)
{
var currentUserId = controllerBase.HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return controllerBase.NotFound();
}
}
但是,我不知道如何返回 OK,因为每个端点的逻辑都不同。
例如 PostSearchFilter 是这样的:
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。有什么建议吗?
为此最好使用中间件。像这样:
public class NotFoundMiddleware
{
private readonly RequestDelegate _next;
public NotFoundMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.GetCurrentUserId().HasValue)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.Headers.Clear();
return;
}
await _next(context);
}
}
我一直在关注这个视频,在第 40 分钟,他们建议使用扩展方法来清理控制器操作中的可重复代码:
https://www.youtube.com/watch?v=h7TJ7eGeT7Q&t=693s
我有这段代码在每个控制器中重复:
var currentUserId = HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return NotFound();
}
执行完后会执行不同的逻辑,它总是 returns 状态码 Ok。
我一直在尝试用扩展方法提取它:
public static IActionResult NotFoundOnEmptyUserId(this ControllerBase controllerBase)
{
var currentUserId = controllerBase.HttpContext.GetCurrentUserId();
if (!currentUserId.HasValue)
{
return controllerBase.NotFound();
}
}
但是,我不知道如何返回 OK,因为每个端点的逻辑都不同。
例如 PostSearchFilter 是这样的:
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。有什么建议吗?
为此最好使用中间件。像这样:
public class NotFoundMiddleware
{
private readonly RequestDelegate _next;
public NotFoundMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
if (!context.GetCurrentUserId().HasValue)
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
context.Response.Headers.Clear();
return;
}
await _next(context);
}
}