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

后端 未结 9 766
轻奢々
轻奢々 2020-12-01 13:38

I have got a web service programmed in c# / asp.net.

[WebService(Namespace = \"http://example.com/\")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProf         


        
相关标签:
9条回答
  • 2020-12-01 14:28

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

                return new HttpStatusCodeResult(HttpStatusCode.Forbidden);
    
    0 讨论(0)
  • 2020-12-01 14:38

    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;
            }
        }
    
    0 讨论(0)
  • 2020-12-01 14:38

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

    return new StatusCodeResult(HttpStatusCode.Forbidden, this);
    
    0 讨论(0)
提交回复
热议问题