How to return 403 Forbidden response as IActionResult in ASP.NET Core

前端 未结 4 556
粉色の甜心
粉色の甜心 2020-12-28 13:28

I would like to return a 403 Forbidden to the client when trying to perform an invalid operation. What is the method I need to use?

I searched over the internet but

相关标签:
4条回答
  • 2020-12-28 13:52

    Alternative to MstfAsan's answer is to use:

    return Forbid();
    

    It is a method on the controller base class that does the same thing.

    Or

    return StatusCode(403);
    

    If you want to return a message, then you must use StatusCode.

    0 讨论(0)
  • 2020-12-28 13:54

    If you don't return ActionResult for response, you can use the following code :

    public List<SomeModel> get()
    {
       ... 
       ... // check logic
       ...
    
       Response.StatusCode = 403;
       return new List<SomeModel>();
    }
    
    0 讨论(0)
  • 2020-12-28 14:08

    You can use return new ForbidResult(); Class declaration is

    public class ForbidResult : ActionResult, IActionResult
    

    For more spesific usages visit https://docs.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.mvc.forbidresult

    0 讨论(0)
  • 2020-12-28 14:12

    When you want to respond with a HTTP 403 status and allow ASP.NET Core's authentication logic to handle the response with its forbidden handling logic (can be configured in your Startup class, and may cause a redirect to another page), use:

    return Forbid();
    

    (same applies to Unauthorized())


    When you want to respond with a HTTP 403 status code from an API and do not want the ASP.NET Core authentication logic to perform any redirect or other action, use:

    return StatusCode(403);
    
    0 讨论(0)
提交回复
热议问题