Asp.Net web service: I would like to return error 403 forbidden
Asked Answered
R

10

41

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?

Revers answered 13/4, 2011 at 13:13 Comment(5)
You return value from service only if user is 'LoggedIn' you must return that 'Result' type from that method.Agouti
and how do I return this 'Result' type ?Revers
You declare your method to return 'Result' type. And you must return object of that type from your method. What is 'Data()'? You cant return something from only one 'if' block, because if that block is false your method will not return anything.Agouti
I thought I can raise an exceptino or something like this and then the web service would return 403Revers
Code 401 would be more appropriate as the user could access the resource if he loggs inMcgregor
R
23

To answer the question completely - this is the code I've used (thank you strider for more information):

[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
        {
            Context.Response.Status = "403 Forbidden"; 
            //the next line is untested - thanks to strider for this line
            Context.Response.StatusCode = 403;
            //the next line can result in a ThreadAbortException
            //Context.Response.End(); 
            Context.ApplicationInstance.CompleteRequest(); 
            return null;
        }
    }
Revers answered 24/2, 2012 at 6:48 Comment(4)
This gives me a ThreadAbortException when used with WebMethod and ScriptMethod.Traweek
try using Context.ApplicationInstance.CompleteRequest() instead of Context.Response.End()Revers
Worth mentioning that Response.Status = "403 Forbidden"; is the complete status that consists of Response.StatusCode and Response.StatusDescription. It might be better to use Response.StatusDescription instead of Response.StatusIsla
In my case it's called "ActionContext" instead of "Context"Glottalized
R
35

If you were using MVC you'd do the following:

            return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
Restrain answered 1/5, 2015 at 17:48 Comment(0)
I
32

You don't need to set both Context.Response.Status and Context.Response.StatusCode. Simply setting

Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden

will automatically set Response.Status for you.

Ignoble answered 11/7, 2012 at 17:49 Comment(1)
It should be a comment on @Revers answerAmaryllis
R
23

To answer the question completely - this is the code I've used (thank you strider for more information):

[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
        {
            Context.Response.Status = "403 Forbidden"; 
            //the next line is untested - thanks to strider for this line
            Context.Response.StatusCode = 403;
            //the next line can result in a ThreadAbortException
            //Context.Response.End(); 
            Context.ApplicationInstance.CompleteRequest(); 
            return null;
        }
    }
Revers answered 24/2, 2012 at 6:48 Comment(4)
This gives me a ThreadAbortException when used with WebMethod and ScriptMethod.Traweek
try using Context.ApplicationInstance.CompleteRequest() instead of Context.Response.End()Revers
Worth mentioning that Response.Status = "403 Forbidden"; is the complete status that consists of Response.StatusCode and Response.StatusDescription. It might be better to use Response.StatusDescription instead of Response.StatusIsla
In my case it's called "ActionContext" instead of "Context"Glottalized
B
7

You can protect all your methods by placing the code in your WebService constructor. This prevents your WebMethod from even being called:

public Service(): base()
{
    if (!GetUser().LoggedIn)
    {
        Context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
        Context.Response.End();
    }
}
Betts answered 5/10, 2011 at 9:43 Comment(2)
Not necessarily correct....I leverage WebMethods through AJAX calls and I have to work to authenticate the user(s) through encrypted cookiesSomite
This doesn't make sense. Your constructor isn't called when your web methods are called. Refer to @bernhardrusch's answer.Jaramillo
E
6

In Asp.Net Web Api 2, you'd use:

return new StatusCodeResult(HttpStatusCode.Forbidden, this);
Exieexigency answered 3/6, 2016 at 11:34 Comment(5)
This does not answer the question at all! The question was relating to a WebService and this is WebApi2Brianbriana
I get what you're saying, but I was fixing some legacy stuff and didn't need to know the answer to a different question that i already knew!Brianbriana
ok my bad ..didn't realize people would still be working on web services.Exieexigency
NP. Wish i wasn't!Brianbriana
@Brianbriana like your profile comment! ;-) Seems legacy crap code is common in automotive field :PMiele
W
3
Context.Response.StatusCode = 403;
Whiz answered 13/4, 2011 at 13:57 Comment(3)
where do I get this response object [I can't access it directly]?Revers
Context.Response.Status = "403 Forbidden"; Context.Response.End(); return null;Revers
Context.Response.Status is a string property, +1 for @bernhardrusch. Correct property to set would be Context.Response.StatusCode if you want to just set 403, an int.Underclassman
B
1

Your web service requests will first encounter your global.asax file. You can check & return there.

Beitnes answered 13/4, 2011 at 20:39 Comment(0)
T
1

aspnet core you can return forbidResult. This is an IResult.

return new ForbidResult();
Tymon answered 21/12, 2021 at 11:55 Comment(0)
C
0

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"

Catholicity answered 13/4, 2011 at 13:56 Comment(0)
R
0

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

Receptacle answered 2/3, 2020 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.