简体   繁体   中英

return a 404 status code and get no contents in response

I throw my custom exception when my StatusCode is 404 the browser get 200 and gets no content but with the other StatusCode things work fine

how to fix this problem and get the 404 in my response not 200

this is my middleware

public static class ExceptionHandlingMiddlewareExtensions
    {
        public static IApplicationBuilder UseNativeGlobalExceptionHandler(this IApplicationBuilder app)
        {
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    try
                    {
                        var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
                        var exception = errorFeature.Error;
                    
                        // Log exception and/or run some other necessary code...

                        var errorResponse = new ErrorResponse();

                        if (exception is HttpException httpException)
                        {
                            errorResponse.StatusCode = httpException.StatusCode;
                            errorResponse.Message = httpException.Message;
                        }

                        context.Response.StatusCode = (int) errorResponse.StatusCode;
                        context.Response.ContentType = "application/json";
                        await context.Response.WriteAsync(errorResponse.ToJsonString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                });
            });

            return app;
        }
    }
}

this is my Controller where I throw 404 StatusCode enter image description here

[HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            throw new HttpException(HttpStatusCode.NotFound, "Not found");
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
                {
                    Date = DateTime.Now.AddDays(index),
                    TemperatureC = rng.Next(-20, 55),
                    Summary = Summaries[rng.Next(Summaries.Length)]
                })
                .ToArray();
        }

在此处输入图像描述

Try to return the not found method from ControllerBase class.

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return NotFound();
        }

Extend your controller to use base class. It should be like this:

public class WeatherForecastController : ControllerBase
{
    ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM