none
Vb .Net: Help returning 401 Error RRS feed

  • Question

  • I'm not getting any logical errors but my code is not returning a 401. Instead it says its redirecting and cant show the code because redirect is not supported or when using postman it just shows the html for a page:

    code:

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
                Dim oImporter As Importer
                Dim oResponse As Domain.Structures.Structures.ReturnResponse
                Dim Input_sr As StreamReader
                Dim sData As String = String.Empty
                Dim bolError As Boolean = False
                Dim obj As New Domain.Models.Order.Order
                Dim sError As New order_response_error
                Dim sResponse As New order_response_success
    
                Try
                    Input_sr = New StreamReader(context.Request.InputStream)
                    sData = Input_sr.ReadToEnd
                    Input_sr.Close()
    
                    If context.Request.ContentType.StartsWith("application/json") Then
                        obj = JsonConvert.DeserializeObject(Of Domain.Models.Order.Order)(sData)
                        If obj.api_key = ConfigurationManager.AppSettings("api_key") Then
                            oImporter = New Importer(sData)
                            oResponse = oImporter.ImportOrder
                            context.Response.StatusCode = HttpStatusCode.OK
    
                            If oResponse.ReturnCode = "Error" Then
                                bolError = True
                                context.Response.StatusCode = HttpStatusCode.Conflict
                                sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
                            Else
                                context.Response.StatusCode = HttpStatusCode.OK
                                sResponse.vendor_order_id = oResponse.Message
                            End If
                        Else
    
                            bolError = True
                            context.Response.StatusCode = HttpStatusCode.Unauthorized
                            sError.Error = "Error: Access Denied"
                        End If
                    Else
                        bolError = True
                        context.Response.StatusCode = HttpStatusCode.BadRequest
                        sError.Error = "Error: Invalid content type"
                    End If
                Catch ex As Exception
                    bolError = True
                    context.Response.StatusCode = HttpStatusCode.BadRequest
                    Utils.ErrorEmail("Order Error!", ex, AttachmentName:="Order.xml", AttachmentData:=sData)
                    sError.Error = String.Format("Error", ex.Message)
                End Try
    
                context.Response.ContentType = "application/json"
    
                If bolError Then
                    context.Response.Write(JsonConvert.SerializeObject(sError))
                Else
                    context.Response.Write(JsonConvert.SerializeObject(sResponse))
                End If
            End Sub
    

    Code snippet:

    bolError = True
                            context.Response.StatusCode = HttpStatusCode.Unauthorized
                            sError.Error = "Error: Access Denied"

    Monday, October 21, 2019 8:41 PM

All replies

  • Have you verified the credentials are correct? Try using Fiddler to see the response headers, see if there is anything useful.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Monday, October 21, 2019 9:42 PM
    Moderator
  • You are looking at too many error possibilities. IMO, if the status is not equal OK, then you just throw the exception with the status error message. All this other error stuff you have going on is unnecessary.

    Just what is it that you are trying to access that needs authorization? Do you even know?


    • Edited by DA924x Tuesday, October 22, 2019 12:19 AM
    Tuesday, October 22, 2019 12:18 AM
  • Have you verified the credentials are correct? Try using Fiddler to see the response headers, see if there is anything useful.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    What do you mean the point of it is to throw an exception because the credentials are wrong. I'm intentionally giving it a bad api key. the issue is I need it to return the 401 error. Currently its not returning any error for unauthorized  


    • Edited by old_School Tuesday, October 22, 2019 7:47 PM
    Tuesday, October 22, 2019 7:44 PM
  • Have you verified the credentials are correct? Try using Fiddler to see the response headers, see if there is anything useful.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    What do you mean the point of it is to throw an exception because the credentials are wrong. I'm intentionally giving it a bad api key. the issue is I need it to return the 401 error. Currently its not returning any error for unauthorized  


    Seriously, your code is very confusing. The de facto is to use HTTPclient(). However, the code I am showing uses WebClient(). There is no try/catch anywhere, becuase Global Exception Handling is used and Webclient() detects that a HTTP status code 200 has not been returned as throws the exception that the GEH handles. 

    Why are you using such legacy code that you are showing? And the HTML is coming back for you becuase the Web server returns the error in HTML format.

    Imports System.Net
    Imports Entities
    Imports Newtonsoft.Json
    
    Namespace WebApi
        Public Class WebApi
            Implements IWebApi
    
            #Region "Project"
            public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
           
            public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi
    
                dim dto as DtoProject
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                    dto = project
                End Using
               
                Return dto
    
            End Function
    
            public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    
            public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub


    Wednesday, October 23, 2019 10:30 AM
  • Have you verified the credentials are correct? Try using Fiddler to see the response headers, see if there is anything useful.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    What do you mean the point of it is to throw an exception because the credentials are wrong. I'm intentionally giving it a bad api key. the issue is I need it to return the 401 error. Currently its not returning any error for unauthorized  


    Seriously, your code is very confusing. The de facto is to use HTTPclient(). However, the code I am showing uses WebClient(). There is no try/catch anywhere, becuase Global Exception Handling is used and Webclient() detects that a HTTP status code 200 has not been returned as throws the exception that the GEH handles. 

    Why are you using such legacy code that you are showing? And the HTML is coming back for you becuase the Web server returns the error in HTML format.

    Imports System.Net
    Imports Entities
    Imports Newtonsoft.Json
    
    Namespace WebApi
        Public Class WebApi
            Implements IWebApi
    
            #Region "Project"
            public Function  GetProjsByUserIdApi(userid As String) as List(of DtoProject) Implements IWebApi.GetProjsByUserIdApi
    
                dim dtoprojects = new List(Of DtoProject)
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectsByUserId?userid=" & userid
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim projects = JsonConvert.DeserializeObject(of List(Of DtoProject))(json)
                    dtoprojects = projects
                End Using
    
                Return dtoprojects
    
            End Function
           
            public Function GetProjByIdApi(id As int32) as DtoProject Implements IWebApi.GetProjByIdApi
    
                dim dto as DtoProject
    
                dim url = "http://localhost/WebApiVB/api/project/GetProjectById?id=" & id
    
                Using webclient As New WebClient
                    dim json  = webclient.DownloadString(url)
                    Dim project = JsonConvert.DeserializeObject(of DtoProject)(json)
                    dto = project
                End Using
               
                Return dto
    
            End Function
    
            public sub CreateProjectApi(dto As DtoProject) Implements IWebApi.CreateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/CreateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
                
            End sub
            
            public sub UpdateProjectApi(dto As DtoProject) Implements IWebApi.UpdateProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/UpdateProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub
    
            public sub DeleteProjectApi(dto As DtoId) Implements IWebApi.DeleteProjectApi
    
                Dim reqString As byte()
    
                Using webclient As New WebClient
    
                    dim url as string = "http://localhost/WebApiVB/api/project/DeleteProject"
                    webClient.Headers("content-type") = "application/json"
                    reqString = Encoding.Default.GetBytes(JsonConvert.SerializeObject(dto, Formatting.Indented))
                    webClient.UploadData(url, "post", reqString)
    
                End Using
    
            End sub


    Preaching to the choir lol 
    Wednesday, October 23, 2019 6:19 PM
  • Preaching to the choir lol 

    But  you still give no explanation as to why you're using such code. Also,  a domain model object doesn't travel aka a business object doesn't travel. A DTO travels between processes.

    https://en.wikipedia.org/wiki/Data_transfer_object

    https://www.codeguru.com/vb/gen/vb_misc/oop/article.php/c7063/Data-Transfer-Object-Pattern-Goes-VBNET.htm

    https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties

    Wednesday, October 23, 2019 8:38 PM