Search code examples
asp.net-mvc-3http-status-code-302http-status-code-401post-redirect-get

return 401 error code on POST, but also redirect to referring page


I'm using the post/redirect/get pattern in my asp.net mvc 3 web application. Typically, if you submit a POST that triggers validation, you get a 302 redirect back to the original page, so the user can correct their form input and resubmit.

But what happens if you want to return a 401 on the POST because the user does not have sufficient permission to POST to that resource? It's easy to return a 401 status code, but then I can't redirect back to the original page. If the user refreshes the page, they will get that "the browser needs to resend the information you previously submitted" prompt, which is the whole point of doing post/redirect/get

Am I better off not trying to return the proper 401 status code and just stick to the typical 302 redirects for all POSTs?


Solution

  • You could potentially append a Location header to your response, e.g:

    HttpContext.Current.Headers['Location'] = 'http://www.gohereinstead.com/';
    

    However I'm not sure how each browser would interpret this alongside a 401 status code.

    EDIT

    Hmm, on closer inspection of the spec, I don't think it will be possible to redirect a POST, in that:

    If the 301 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.

      Note: When automatically redirecting a POST request after
      receiving a 301 status code, some existing HTTP/1.0 user agents
      will erroneously change it into a GET request.