【问题标题】:HTTP interceptor display multiple message problemHTTP拦截器显示多条消息问题
【发布时间】:2019-11-25 17:29:08
【问题描述】:

在我的项目中(.net core 2.2 + angular 8)。为了显示一个错误 HttpInterceptor 它工作得很好, 但对于多条消息,它也可以工作,但没有显示正确的错误消息。 我得到了类似的东西:

[object Object] One or more validation errors occurred. 400 0HLRCTBS664E8:00000002

我的拦截器看起来像:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(req).pipe(
            catchError(error => {
                if (error instanceof HttpErrorResponse) {
                    if (error.status === 401) {
                        return throwError(error.statusText);
                    }
                    const applicationError = error.headers.get('Application-Error');
                    if (applicationError) {
                        console.error(applicationError);
                        return throwError(applicationError);
                    }
                    const serverError = error.error;
                    let modalStateErrors = '';
                    if (serverError && typeof serverError === 'object') {
                        for (const key in serverError) {
                            if (serverError[key]) {
                                modalStateErrors += serverError[key] + '\n';
                            }
                        }
                    }
                    return throwError(modalStateErrors || serverError || 'Server Error');
                }
            })
        )
    }
}

export const ErrorInterceptorProvide = {
    provide: HTTP_INTERCEPTORS,
    useClass: ErrorInterceptor,
    multi: true
}

我使用的 dto 类:

    [Required(ErrorMessage = "username is required")]
    public string Username { get; set; }

    [Required(ErrorMessage = "password is required")]
    [StringLength(20, MinimumLength = 6, ErrorMessage = "Password should be between 6 and 20 
    characters")]
    public string Password { get; set; }

我的 Startup 类如下所示:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler(builder =>
            {
                builder.Run(async context =>
                {
                    context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;

                    var error = context.Features.Get<IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        context.Response.AddApplicationError(error.Error.Message);
                        await context.Response.WriteAsync(error.Error.Message);
                    }
                });
            });                
        }


        app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        app.UseAuthentication();

        app.UseMvc();

    }
 }

应用错误扩展方法:

    public static class Extensions
    {
        public static void AddApplicationError(this HttpResponse response, string message)
        {
            response.Headers.Add("Application-Error", message);
            response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
            response.Headers.Add("Access-Control-Allow-Origin", "*");
        }
    }

【问题讨论】:

    标签: c# angular http asp.net-core


    【解决方案1】:

    您的 API 中的 automatic 400 responses 似乎存在问题。

    避免它的最佳方法是抑制此错误。

    要禁用自动 400 行为,请设置 将ModelStateInvalidFilter 属性抑制为true。添加以下内容 Startup.ConfigureServices 中突出显示的代码:

    这是文章中包含的代码:

    services.AddMvc()
    
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
    

    微软recommended way in github, is here

    【讨论】:

    • 我试过了,但是没有用。有趣的部分是用于显示有效的单个消息
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2023-03-12
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    相关资源
    最近更新 更多