Asp.net core 如何制作;出现一个或多个验证错误;提出一个例外?
我在Core 3.1上运行一个WebAPI,我的一个端点除了JSON之外,还有一个模型,该模型的字段具有Asp.net core 如何制作;出现一个或多个验证错误;提出一个例外?,asp.net-core,asp.net-core-3.1,Asp.net Core,Asp.net Core 3.1,我在Core 3.1上运行一个WebAPI,我的一个端点除了JSON之外,还有一个模型,该模型的字段具有[必需]属性,如下所示: public class Vendor { public int ID { get; set; } [Required(ErrorMessage = "UID is required")] <<<------ required attribute public string UI
[必需]
属性,如下所示:
public class Vendor
{
public int ID { get; set; }
[Required(ErrorMessage = "UID is required")] <<<------ required attribute
public string UID { get; set; }
}
尽管此输出信息丰富且清晰,但它与我的API通过ExceptionFilter生成的其他错误输出不一致。是否也可以将此错误路由到异常筛选器
这是我的Startup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
Common.Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddMvc().AddXmlDataContractSerializerFormatters();
services.AddMvc().AddMvcOptions(options =>
{
options.EnableEndpointRouting = false;
});
services.AddMvcCore(options => options.OutputFormatters.Add(new XmlSerializerOutputFormatter()));
services.AddOptions();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
//Middleware for exception filtering
app.UseMiddleware<ErrorHandlingMiddleware>(new ErrorHandlingMiddlewareOptions { logger = logger });
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseMvc(routes =>
{
routes.MapRoute("EndpointNotFound", "{*url}", new { controller = "Error", action = "EndpointNotFound" });
});
}
}
公共类启动
{
公共启动(IConfiguration配置)
{
配置=配置;
Common.Configuration=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddControllers();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddMvc().AddXmlDataContractSerializerFormatters();
services.AddMvc().addmvcopions(选项=>
{
options.EnableEndpointRouting=false;
});
services.AddMvcCore(options=>options.OutputFormatters.Add(新的XmlSerializerOutputFormatter());
services.AddOptions();
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境、ILogger记录器)
{
//异常过滤中间件
使用中间件(新的ErrorHandlingMiddlewareOptions{logger=logger});
app.UseStaticFiles();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
app.UseMvc(路由=>
{
MapRoute(“EndpointNotFound”,“{*url}”,new{controller=“Error”,action=“EndpointNotFound”});
});
}
}
为了实现此功能,您需要实现此问题中描述的您自己的模型验证器:您可以在mvc服务或控制器服务中添加过滤器
此筛选器返回错误请求
services.AddControllers(option =>
{
option.Filters.Add<ValidationFilter>();
});
我已经创建了这样的错误模型
public class ErrorModel
{
public string FieldName { get; set; }
public string Message { get; set; }
}
错误响应如下所示
public class ErrorResponse
{
public List<ErrorModel> Error { get; set; } = new List<ErrorModel>();
public bool Successful { get; set; }
}
公共类错误响应
{
公共列表错误{get;set;}=new List();
公共bool成功{get;set;}
}
您可能想看看伟大的图书馆
样本:
构建一个绑定DTO的验证器模块,并创建一组规则
公共类CustomerValidator:AbstractValidator{
公共CustomerValidator(){
RuleFor(x=>x.姓氏).NotEmpty();
RuleFor(x=>x.Forename).NotEmpty().WithMessage(“请指定名字”);
规则(x=>x.Discount).NotEqual(0).When(x=>x.HasDiscount);
RuleFor(x=>x.Address).Length(20250);
RuleFor(x=>x.Postcode).Must(BeAValidPostcode).WithMessage(“请指定有效的邮政编码”);
}
私有布尔BeAValidPostcode(字符串邮政编码){
//自定义邮政编码验证逻辑在这里
}
}
通过DI将其注入控制器:
services.AddControllers()
.AddFluentValidation(s=>
{
s、 ValidatorOptions.CascadeMode=CascadeMode.Stop;
s、 RunDefaultMvcValidationAfterFluentValidationExecutes=false;
s、 ValidatorOptions.LanguageManager.Culture=新文化信息(“en-US”);
s、 RegisterValidatorsFromAssemblyContaining();
...
//更多验证器
});
- 这样你的代码看起来组织得很好李>
- 您可以去掉散布在代码中的数据注释
- 个性化错误消息和验证
您可能还想检查为什么在使用web API时,在控制器上实现可能是一种可行的方法。我刚刚更改了http方法,可以很好地解决相同的问题 [HttpPost(“验证”)]
public IActionResult Authenticate([FromBody]AuthenticateModel model)我想通过答案和microsoft文章了解如何设置属性过滤器,但仍然无法使其在“OnActionExecuting”中运行mu自定义登录。。。能否提供一个简短的代码段,其中包含startup.cs的关键组件和其他相关项目?谢谢如果您在默认情况下使用[ApiController],apibehavior将自动返回HTTP 400。您可以抑制这种情况(意味着您必须自己检查模型状态-我个人不建议这样做,因为它可能容易出错),或者通过
InvalidModelStateResponseFactory
自定义错误输出。这是对后者的一个解释。我不建议仅为此创建自定义操作筛选器。顺便说一句,如果您仍想使用操作筛选器路线(自己手动检查ModelState.IsValid
),请检查官方文档中的。我在您进行布局时已详细实施了所有操作,但仍会收到400个一般错误:(
public class ErrorModel
{
public string FieldName { get; set; }
public string Message { get; set; }
}
public class ErrorResponse
{
public List<ErrorModel> Error { get; set; } = new List<ErrorModel>();
public bool Successful { get; set; }
}