C# 如何在 ASP.NET 页面中以编程方式生成 401 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/217678/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 18:32:14  来源:igfitidea点击:

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

c#asp.netiisasp.net-2.0

提问by Detlef D. Doerscheln

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.

如您所见,这是来自非 Web 开发人员的问题。我想要一个 ASPX 页面,在某些情况下,它可以从代码生成 401 错误。理想情况下,它将显示 IIS 标准页面。

采纳答案by Jon Skeet

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

设置Response.StatusCode然后 - 如果您需要停止执行 - 调用Response.End()

回答by Mitchel Sellers

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

根据MSDN,您应该可以只使用以下内容。

Throw New HttpException(401, "Auth Failed")

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

编辑看到其他响应设置状态代码会更合适。

回答by Mark Cidade

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

回答by Brian Ferguson

I think I still prefer:

我想我还是更喜欢:

throw new HttpException(401, "Auth Failed")

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

我认为该Response.StatusCode方法不会触发 web.config 文件中定义的自定义错误,例如

<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 ELMAHor something, and I don't think the Response.StatusCodemethod would be logged there, either.

此外,您可能正在使用应用程序范围的错误日志记录工具,如ELMAH或其他东西,我认为该Response.StatusCode方法也不会记录在那里。

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.StatusCodemethod in that case.

注意:我现在看到这个问题说,理想情况下,应该显示标准的 IIS 错误页面。显然,不需要自定义错误页面。Response.StatusCode在这种情况下,我会使用该方法。

回答by AnthonyVO

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();