Asp.Net Web 服务:我想返回错误 403 禁止
我有一个用 c# / asp.net 编程的网络服务。
[WebService(Namespace = "http://example.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class Service: System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result GetData()
{
User user = GetUser();
if (user.LoggedIn)
{
return GetData();
}
else
{
// raise exception -> return error 403
}
}
如何从该 Web 服务返回错误 403?我可以抛出异常 - 但这显示了异常而不是他的错误。
有什么想法吗?
I have got a web service programmed in c# / asp.net.
[WebService(Namespace = "http://example.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
[System.ComponentModel.ToolboxItem(false)]
public class Service: System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result GetData()
{
User user = GetUser();
if (user.LoggedIn)
{
return GetData();
}
else
{
// raise exception -> return error 403
}
}
How is it possible to return error 403 out of this web service? I can throw an exception - but this shows the exeption and not his error.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
如果您使用 MVC,您将执行以下操作:
If you were using MVC you'd do the following:
您无需同时设置
Context.Response.Status
和Context.Response.StatusCode
。只需设置即可自动为您设置
Response.Status
。You don't need to set both
Context.Response.Status
andContext.Response.StatusCode
. Simply settingwill automatically set
Response.Status
for you.为了完全回答这个问题 - 这是我使用的代码(感谢 strider 提供更多信息):
To answer the question completely - this is the code I've used (thank you strider for more information):
您可以通过将代码放置在 WebService 构造函数中来保护所有方法。这甚至会阻止您的 WebMethod 被调用:
You can protect all your methods by placing the code in your WebService constructor. This prevents your WebMethod from even being called:
在 Asp.Net Web Api 2 中,您可以使用:
In Asp.Net Web Api 2, you'd use:
您的 Web 服务请求将首先遇到您的 global.asax 文件。您可以检查&返回那里。
Your web service requests will first encounter your global.asax file. You can check & return there.
aspnet core 你可以返回forbidResult。这是一个 IResult。
aspnet core you can return forbidResult. This is an IResult.
Forbidden 403 是由于访问您网站上的禁止内容而导致的。我认为您在这里想要的是返回一条消息作为结果的一部分,即“用户未登录”
Forbidden 403 would be a result of access to forbidden content on your website. I think what you want here is to return a message as part of your Result that is "User is not logged on"
return Forbid();
创建一个 ForbidResult(默认情况下为 Status403Forbidden)。https:// learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.forbid?view=aspnetcore-3.1
The
return Forbid();
creates a ForbidResult (Status403Forbidden by default).https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controllerbase.forbid?view=aspnetcore-3.1