从 WCF 服务返回 401

发布于 2024-08-16 00:10:09 字数 29 浏览 3 评论 0原文

如何从 WCF 服务返回 HTTP 401?

How can I return a HTTP 401 from a WCF service?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

_失温 2024-08-23 00:10:09

如果您正在编程 REST 服务,可以通过以下方式完成:

private IWebOperationContext context = new WebOperationContextWrapper(WebOperationContext.Current); // Get the context

context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401

If you are programming a REST-service it can be done this way:

private IWebOperationContext context = new WebOperationContextWrapper(WebOperationContext.Current); // Get the context

context.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized; // Set the 401
醉南桥 2024-08-23 00:10:09
throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);

笔记:

MSDN:使用 WCF REST 端点(WebHttpBinding 和
WebHttpBehavior 或 WebScriptEnablingBehavior)上的 HTTP 状态代码
相应地设置响应。但是,WebFaultException 可以是
与非 RE​​ST 端点一起使用,其行为类似于常规端点
错误异常。

throw new WebFaultException(System.Net.HttpStatusCode.Unauthorized);

Notes:

MSDN: When using a WCF REST endpoint (WebHttpBinding and
WebHttpBehavior or WebScriptEnablingBehavior) the HTTP status code on
the response is set accordingly. However, WebFaultException can be
used with non-REST endpoints and behaves like a regular
FaultException.

公布 2024-08-23 00:10:09

如果您使用 WCF REST Starter Kit 中的 WebServiceHost2 工厂,您还可以抛出特定的 WebProtocolException 并指定 HTTP 返回代码:

替代文字
(来源: robbagby.com)

alt 文本
(来源: robbagby.com)

替代文字
(来源: robbagby.com)

还有一个 HttpStatusCode.Unauthorized 对应于 401 状态代码。

请参阅 Rob Bagby 的优秀博客文章 使用 WCF REST 进行有效的错误处理< /a> 有关指定 HTTP 返回代码的各种方法的更多详细信息。 (屏幕截图来自 Rob 的博客文章 - 他应得的所有荣誉。)

If you're using the WebServiceHost2 factory from the WCF REST Starter Kit, you can also throw specific WebProtocolException and specify a HTTP return code:

alt text
(source: robbagby.com)

alt text
(source: robbagby.com)

alt text
(source: robbagby.com)

There's also a HttpStatusCode.Unauthorized which corresponds to the 401 status code.

See Rob Bagby's excellent blog post Effective Error Handling with WCF REST for more detail on the various ways of specifying HTTP return codes. (screenshots are from Rob's blog post - he deserves all the credit for this.)

梦幻之岛 2024-08-23 00:10:09

根据您需要进行授权检查的时间,您可以使用如下内容在 HttpModule 中执行此操作:

HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.End();

Depending on when you need to do the authorization check, you could do it in an HttpModule using something like the following:

HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.End();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文