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

后端 未结 6 1842
攒了一身酷
攒了一身酷 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:24

    The Microsoft.AspNet.Mvc.Controller base class exposes a HttpBadRequest(string) overload which takes an error message to return to the client. So from within a controller action, you could call:

    return HttpBadRequest("Bad Request.");
    

    Ultimately my nose says any private methods called from within a controller action should either be fully http-context-aware and return an IActionResult, or perform some other small task completely isolated from the fact that it's inside of an http pipeline. Granted this is my personal opinion, but a class that performs some piece of business logic should not be returning HTTP status codes, and instead should be throwing its own exceptions which can be caught and translated at the controller/action level.

提交回复
热议问题