ASP.NET Core equivalent of ASP.NET MVC 5's HttpException

后端 未结 6 1835
攒了一身酷
攒了一身酷 2020-12-02 11:59

In ASP.NET MVC 5 you could throw a HttpException with a HTTP code and this would set the response like so:

throw new HttpException((int)HttpStatusCode.BadReq         


        
6条回答
  •  情歌与酒
    2020-12-02 12:44

    There is no equivalent in ASP.NET Core itself. As others have said, the way to implement this is with a middleware and your own exceptions.

    The Opw.HttpExceptions.AspNetCore NuGet package does exactly this.

    Middleware and extensions for returning exceptions over HTTP, e.g. as ASP.NET Core Problem Details. Problem Details are a machine-readable format for specifying errors in HTTP API responses based on https://tools.ietf.org/html/rfc7807. But you are not limited to returning exception results as Problem Details, but you can create your own mappers for your own custom formats.

    It is configurable and well documented.

    Here is the list of provided exceptions out of the box:

    4xx
    • 400 BadRequestException
    • 400 InvalidModelException
    • 400 ValidationErrorException
    • 400 InvalidFileException
    • 401 UnauthorizedException
    • 403 ForbiddenException
    • 404 NotFoundException
    • 404 NotFoundException
    • 409 ConflictException
    • 409 ProtectedException
    • 415 UnsupportedMediaTypeException
    5xx
    • 500 InternalServerErrorException
    • 500 DbErrorException
    • 500 SerializationErrorException
    • 503 ServiceUnavailableException

提交回复
热议问题