0

I'm having an issue with my code not returning Json response. I've never built an API using ASHX before. I have checked my Json string being created and it appears to be good.

The returned serialized json looks like this:

"{""Error"":""Error: Import: Unknown SKU Received!""}" 

This is the correct message that should be returned. Instead I get Bad Request as a response. Not generating any errors on my code side.

Code Snippet:

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
    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.BadRequest
                    sError.Error = oResponse.ReturnCode + ": " + oResponse.Message
                    'sError.Error = String.Format(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"
                'sError.Error = String.Format("Error", "Access Denied")
            End If
        Else
            bolError = True
            context.Response.StatusCode = HttpStatusCode.BadRequest
            sError.Error = "Error: Invalid content type"
            'sError.Error = String.Format("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

Error Response from client:

Error: Cache-Control:
private Content-Type: application/json; charset=utf-8 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-SourceFiles: =?UTF-8?B?XFxhd2FyZGdyYXBoaWNzLmNvbVxkYXRhXFVzZXJzXG1ob2xtZXNcRGVza3RvcFxDb2xsYWdlXENvbGxhZ2VcQ29sbGFnZS5XZWIuUG9ydGFsXGFwaVx0ZXN0b3JkZXIxLmFzaHg=?= X-Powered-By: ASP.NET Access-Control-Allow-Origin: * Access-Control-Allow-Methods:
GET, POST, OPTIONS Access-Control-Allow-Headers: X-Requested-With,Content-Type Date:
Mon, 14 Oct 2019 14:47:57 GMT Content-Length: 48 bytes COMPLETE REQUEST HEADERS pretty Sec-Fetch-Mode: cors Origin: chrome-extension://aejoelaoggembcahagimdiliamlcdmfm User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36 Content-Type: application/json Accept: / Sec-Fetch-Site: cross-site Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cookie: AspxAutoDetectCookieSupport=1

mholmes
  • 177
  • 2
  • 14
  • Can you include the full error message you receive on the client side (headers as well). There are several places in your code that set `BadRequest` so right now it's kind of difficult to know if they are or aren't the root cause.... – Stephen Byrne Oct 14 '19 at 14:42
  • How are you sending the request? Have you tried logging the received `context.Request.ContentType` on the server? – Joel Coehoorn Oct 14 '19 at 14:46
  • You are sending out an `HttpStatusCode.BadRequest` *and* a body. It would appear you just fail to [read the body](https://stackoverflow.com/q/692342/11683) on the receiving side. – GSerg Oct 14 '19 at 14:46
  • I have stepped through the code and no errors occur on my code end. No exceptions occur – mholmes Oct 14 '19 at 14:55
  • Have you tried a simplified scenario? I mean, comment out all the logic and just straight up return some JSON from that handler (i.e. `context.Response.Write("{'foo':'1'}"`). If that works, then the issue is in your code. If it doesn't, then there is something else going on. What is the calling client? Also I don't actually see anywhere in that error that says "BadRequest", are you *sure* you are getting HTTP 400 on the response? – Stephen Byrne Oct 14 '19 at 15:00

1 Answers1

1

You only have one place in your code where you return a custom message from the server, and with a 'BadRequest', on these lines:

context.Response.StatusCode = HttpStatusCode.BadRequest
sError.Error = oResponse.ReturnCode + ": " + oResponse.Message

That means your business logic is returning this (I can't say appropriately or not). You need to trace through the business logic to find the logic that is presenting the bad SKU message. From that point of view, the ASHX looks to be working correctly.

AlienFromCA
  • 863
  • 12
  • 19