How to generate an 401 error programmatically in an ASP.NET page

巧了我就是萌 提交于 2019-12-17 17:41:14

问题


As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page.


回答1:


Set Response.StatusCode and then - if you need to stop execution - call Response.End().




回答2:


Response.StatusCode = 401;
Response.End();



回答3:


I think I still prefer:

throw new HttpException(401, "Auth Failed")

I don't think the Response.StatusCode method triggers custom errors defined in the web.config file, e.g.

<customErrors mode="On" defaultRedirect="GenericErrorPage.htm">
     <error statusCode="401" redirect="AuthFailed.htm" />
     <error statusCode="403" redirect="NoAccess.htm" />
     <error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

Throwing a new exception definitely triggers custom errors.

Also, you might be using an application-wide error logging facility, like ELMAH or something, and I don't think the Response.StatusCode method would be logged there, either.

Note: I see now the question said that, ideally, the standard IIS error page should be shown. Obviously, the custom error pages are not wanted. I would use the Response.StatusCode method in that case.




回答4:


You should be able to just use the following, according to MSDN.

Throw New HttpException(401, "Auth Failed")

Edit After seeing the other responses setting the status code would be more appropriate.




回答5:


One additional comment.

If a portion of the page has already been written to the output buffer then it is important that you clear any buffered content or the page may not appear correctly.

This is quite likely in a templated environment. e.g. Master pages...

Response.ClearContent();
Response.StatusCode = 401;
Response.End();


来源:https://stackoverflow.com/questions/217678/how-to-generate-an-401-error-programmatically-in-an-asp-net-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!