Which HTTP Status Codes to cover for MVC error handling

后端 未结 4 2197
甜味超标
甜味超标 2021-02-13 15:09

I\'m currently developing custom error pages in my error handling code for my MVC application. But I\'m unclear as to which HTTP status codes I\'m meant to cover.

4条回答
  •  花落未央
    2021-02-13 15:37

    I'm trying to find out the answer also. My code looks scarily like yours. This is a great question with so few views, I've set a bounty on this question. I myself have handled the following codes so far:

    
      
      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      
    
    

    My reasoning is as follows:

    • 400 - Controllers have the BadRequest() method built in and you may want to return this when a parameter passed to the action is invalid.
    • 401 - Applying the Authorize attribute to a controller or action causes a 401 Unauthorized response. Controllers also have the Unauthorized() method built in.
    • 403.14 - Redirect these to 404 Not Found responses as a Forbidden is just plain wrong (See Securing your web.config and Troy Hunt's blog for more information).
    • 404 - Thrown when the user browses to a page not found.
    • 500 - Thrown when something goes catastrophically wrong.

    Overall I feel you should handle those codes that you yourself are going to use. The problem is that IIS does all kinds of strange things and we need to handle some of it's incorrect or invalid responses such as the 403.14 I listed above.

    Here is a complete list of IIS HTTP Status Codes and Sub-Status Codes which might be useful to our cause. I have a feeling the 403 Forbidden response should also be supported as it seems to be a fairly prominent response thrown by IIS.

    One interesting thing I discovered while Googling is that navigating to:

    yoursite/
    

    Returns a 500 Internal Server from IIS. I feel this should return a 404. The IIS error page does not tell us what the Sub-Status Code is and I would be interested to know how we can find out, so that we can redirect the 500.Something to a 404 Not Found page.

    Here is a link to the GitHub page for the ASP.NET MVC Boilerplate project, for which I am doing this research and where you can look at my code.

提交回复
热议问题