none
ASHX: Unreachable API RRS feed

  • Question

  • I'm not sure what I'm doing wrong. I have never used ASHX before. I have built my API's in c# MVC. So building it in VB ASHX is new to me. I'm trying to test this API locally but get a 302 error when I call the end point or what I think is the end point. Here is my code:

    Test endpoint:

    http://localhost:64222/api/order.ashx

    Code

    Imports System.Web
    Imports System.Web.Services
    Imports System.IO
    Imports Collage.Business
    Imports Collage.Helpers.Components
    Imports Newtonsoft
    Imports Newtonsoft.Json
    Imports System.Configuration
    
    Namespace api
        Public Class order
            Implements System.Web.IHttpHandler
    
            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 = 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 = String.Format("Error", "Access Denied")
                        End If
                    Else
                        bolError = True
                        context.Response.StatusCode = HttpStatusCode.BadRequest
                        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
    
            '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 sReturn As String
    
            '    Try
            '        Input_sr = New StreamReader(context.Request.InputStream)
            '        sData = Input_sr.ReadToEnd
            '        Input_sr.Close()
    
            '        If context.Request.ContentType.StartsWith("application/xml") Then
            '            oImporter = New Importer(sData)
            '            oResponse = oImporter.ImportOrder
            '            context.Response.StatusCode = HttpStatusCode.OK
    
            '            If oResponse.ReturnCode = "Error" Then
            '                sReturn = String.Format(Utils._sOrderErrorXML, oResponse.Message, oResponse.Message)
            '            Else
            '                sReturn = String.Format(Utils._sOrderOkXML, oResponse.Message)
            '            End If
            '        Else
            '            sReturn = String.Format(Utils._sOrderErrorXML, "Error", "Invalid content type")
            '        End If
            '    Catch ex As Exception
            '        context.Response.StatusCode = HttpStatusCode.BadRequest
    
            '        Utils.ErrorEmail("Order Error!", ex, AttachmentName:="Order.xml", AttachmentData:=sData)
    
            '        sReturn = String.Format(Utils._sOrderErrorXML, "Error", ex.Message)
            '    End Try
    
            '    context.Response.ContentType = "application/xml"
            '    context.Response.Write(sReturn)
            'End Sub
    
            ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
                Get
                    Return False
                End Get
            End Property
        End Class
    End Namespace

    Json:

    {
      "order_id": "1234567",
      "api_key": "sx1rz2b1xuZvHYyVlmkBz4cuqwmha41l",
      "shipping_first_name": "John",
      "shipping_last_name": "Doe",
      "shipping_address1": "123 Fake St.",
      "shipping_address2": "",
      "shipping_city": "Somecity",
      "shipping_state": "CA",
      "shipping_zip": "90210",
      "shipping_country": "US",
      "shipping_email": "support@collage.com",
      "shipping_phone": "888-797-1902",
      "shipping_method": "TBD",
      "items": [
        {
          "sku": "card-silk120-5x7",
          "quantity": 20,
          "substrate": "80851",
          "diecut_shape": "SQUARE_CORNER",
          "images": [
            {
              "page": 0,
              "url": "http://api.collage.com/v2.php/renderondemand/3125400792_47d5866043b50451.jpg"
            },
            {
              "page": 1,
              "url": "http://api.collage.com/v2.php/renderondemand/3125400794_4ec8fade99f86063.jpg"
            }
          ]
        },
        {
          "sku": "card-silk110-5x7",
          "quantity": 50,
          "substrate": "80850",
          "diecut_shape": "ROUND_CORNER",
          "images": [
            {
              "page": 0,
              "url": "http://api.collage.com/v2.php/renderondemand/3125400792_47d5866043b50451.jpg"
            }
          ]
        },
        {
          "sku": "envelope-5x7",
          "quantity": 20
        },
        {
          "sku": "envelope-5x7",
          "quantity": 50
        }
      ]
    }

    Not sure if my endpoint is the issue or something else. I've never built an API like this before so any help is great.

    Monday, October 14, 2019 1:20 PM

Answers

  • Perhaps place this in Global.asax in Application_Start()

    GlobalConfiguration.Configuration.Formatters.Clear()
    GlobalConfiguration.Configuration.Formatters.Add(New JsonMediaTypeFormatter())


    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

    • Marked as answer by old_School Tuesday, October 15, 2019 3:22 PM
    Monday, October 14, 2019 2:29 PM
    Moderator
  • I rebuilt my solution and it started working.
    • Marked as answer by old_School Monday, October 14, 2019 3:14 PM
    Monday, October 14, 2019 3:14 PM

All replies

  • Im able to hit my API now but its not returning JSON. I'm not what I'm doing wrong here. I'm hitting this after I return. I have no idea what this is:

    Imports System.Web
    Imports System.Net
    
    Namespace Helpers.Components
        Public Class CORSModule
            Implements IHttpModule
    
            Private _context As System.Web.HttpApplication
    
            Public Sub Dispose() Implements System.Web.IHttpModule.Dispose
                'RemoveHandler _context.PreSendRequestHeaders, AddressOf OnPreSendRequestHeaders
            End Sub
    
            Public Sub Init(context As System.Web.HttpApplication) Implements System.Web.IHttpModule.Init
                _context = context
                AddHandler _context.PreSendRequestHeaders, AddressOf OnPreSendRequestHeaders
            End Sub
    
            Private Sub OnPreSendRequestHeaders(ByVal s As Object, ByVal e As EventArgs)
                Dim context As HttpApplication = CType(s, HttpApplication)
    
                If context.Request.HttpMethod = "OPTIONS" Then
                    context.Response.StatusCode = HttpStatusCode.OK
                End If
            End Sub
        End Class
    End Namespace

    Monday, October 14, 2019 2:10 PM
  • I think I found the issue but not sure how to resolve it. I have a string of "{""Error"":""Error: Import: Unknown SKU Received!""}" being created when I convert to json. When I try to convert this to Json using http://json2csharp.com/ I get an error. The issue is I think I have to man " in the string 
    Monday, October 14, 2019 2:24 PM
  • Perhaps place this in Global.asax in Application_Start()

    GlobalConfiguration.Configuration.Formatters.Clear()
    GlobalConfiguration.Configuration.Formatters.Add(New JsonMediaTypeFormatter())


    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

    • Marked as answer by old_School Tuesday, October 15, 2019 3:22 PM
    Monday, October 14, 2019 2:29 PM
    Moderator
  • I rebuilt my solution and it started working.
    • Marked as answer by old_School Monday, October 14, 2019 3:14 PM
    Monday, October 14, 2019 3:14 PM