我需要实现自定义操作过滤器,以便可以自定义BadRequest
响应,以针对端点参数的模型状态进行调用。
自定义操作过滤器看起来像-
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace RestAPI.Extensions
{
public class ValidateActionParametersAttribute:ActionFilterAttribute
{
public ValidateActionParametersAttribute()
{
//constructor gets called when endpoint is called
//with empty body , but not the overridden methods
}
public override void OnActionExecuted(ActionExecutedContext context)
{
throw new System.NotImplementedException();
}
public override void OnActionExecuting(ActionExecutingContext context)
{
//check various scenarios
//like if model is null.
//like arguments passed in correct syntax or not.
base.OnActionExecuting(context);
}
}
然后我在Startup.cs,ConfigureServices中注册此过滤器。
//add action filter
services.AddScoped<ValidateActionParametersAttribute>();
我的POST
操作方法。
//My Controller is inherited from other controller which being base inherits from ControllerBase
[Produces(MediaTypeNames.Application.Json)]
public class AuthController : BaseApiController
{
[Route("login")]
[HttpPost]
[ServiceFilter(typeof(ValidateActionParametersAttribute))]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status405MethodNotAllowed)]
[ProducesResponseType(StatusCodes.Status503ServiceUnavailable)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<ActionResult> Login([FromBody]LoginInputModel login)
{
//endpoint logic
}
}
最后,我传递给Login
端点的模型
/// <summary>
/// model to be used as paramter body for login.
/// </summary>
public class LoginInputModel
{
[EmailAddress]
[Required(ErrorMessage ="EmailId is needed")]
[Display(Description ="Email for login",ResourceType =typeof(string))]
public string Email { get; set; }
[DataType(DataType.Password)]
[Required]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
我想返回具有自定义结构的BadRequest
响应,但就我而言,调试器只是没有使用OnActionExecuted()
方法。.
我正在尝试使用空主体或无效输入来调用端点 登录正文。
不执行操作过滤器,而是以某些自动生成的格式返回BadRequest
响应。
有人可以帮我解决这个问题吗?