locked
Best way to insert response into database RRS feed

  • Question

  • User-1104215994 posted

    Hello,

    In my controller method, I would like to insert the response object into the database. Would you please check my code and give me feedback?

    Here is my model:

    public class InitiateResponse
        {
    
            public int Id { get; set; }
            public string referenceId { get; set; }
            public string productCode { get; set; }
            public int quantity { get; set; }
            public string version { get; set; }
            public string signature { get; set; }
            public string ApplicationCode { get; set; }
            public string validatedToken { get; set; }
            public DateTime? responseDateTime { get; set; }
            public string initialResultCode { get; set; }        
           
        }

    Here is my controller method:

     [HttpPost, Route("initiation")]
            public async Task<IHttpActionResult> PostInitiate(InitiateRequest initiate)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
                //Adding Request into database
                context.InitiatesRequests.Add(initiate);
                await context.SaveChangesAsync();
    
                var httpClient = new HttpClient();
                
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(initiate),
                    Encoding.UTF8,
                    "application/json"
                );
    
               var response =
                    await httpClient.PostAsync("https://teststore.gamesultan.com/purchaseinitiation", content);
    
                var htmlResponse = string.Empty;
                if (response != null)
                {
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            return NotFound();
    
                        case HttpStatusCode.InternalServerError:
                            return InternalServerError();
    
                        case HttpStatusCode.OK:
                            htmlResponse = await response.Content.ReadAsStringAsync();
                            //Adding Response into database
                            context.InitiateResponses.Add(JsonConvert.DeserializeObject<InitiateResponse>(htmlResponse));
                            await context.SaveChangesAsync();
                            return Ok(htmlResponse);
    
                        case HttpStatusCode.BadRequest:
                            return BadRequest();
                            
                        case HttpStatusCode.Unauthorized:
                            return Unauthorized();
                            
                        case HttpStatusCode.RequestTimeout:
                            return InternalServerError(); 
                            
                        default:
                            htmlResponse = await response.Content.ReadAsStringAsync();
                            break;
                    }
                }
    
                return Ok(htmlResponse);
    
            }

    Saturday, March 9, 2019 9:30 AM

All replies

  • User753101303 posted

    Hi,

    context comes from where ? You are seeing errors or problems sometimes ? It's best to be always explicit rather than letting others to guess from your code.

    Saturday, March 9, 2019 1:02 PM
  • User-1104215994 posted

    Here is clearer code portion :) Is this bold portion good enough? Any suggestions? By the way, I can't test the bold portion, service I am calling returns 404. Until the service is OK, I need to know if it is good enough.

    [RoutePrefix("api/v2/pin")]
        public class InitiatesController : ApiController
        {
            private readonly EPINMiddleWareAPIContext context;
    
            public InitiatesController(EPINMiddleWareAPIContext context)
            {
                this.context = context;
            }
    
    
            // POST: api/Game
            //[RequireHttps] For Prod Only
            [HttpPost, Route("initiation")]
            public async Task<IHttpActionResult> PostInitiate(InitiateRequest initiate)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }
    
    
                using (MD5 md5Hash = MD5.Create())
                {
                    string hash = GetMd5Hash(md5Hash, source);
    
                }
    
    
                //Adding Request into database
                context.InitiatesRequests.Add(initiate);
                await context.SaveChangesAsync();
    
                var httpClient = new HttpClient();
                
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(initiate),
                    Encoding.UTF8,
                    "application/json"
                );
    
               var response =
                    await httpClient.PostAsync("https://test.com/purchaseinitiation", content);
    
                var htmlResponse = string.Empty;
                if (response != null)
                {
                    switch (response.StatusCode)
                    {
                        case HttpStatusCode.NotFound:
                            return NotFound();
    
                        case HttpStatusCode.InternalServerError:
                            return InternalServerError();
    
                        case HttpStatusCode.OK:
                            htmlResponse = await response.Content.ReadAsStringAsync();
                            //Adding Response into database
                            context.InitiateResponses.Add(JsonConvert.DeserializeObject<InitiateResponse>(htmlResponse));
                            await context.SaveChangesAsync();
                            return Ok(htmlResponse);
    
                        case HttpStatusCode.BadRequest:
                            return BadRequest();
                            
                        case HttpStatusCode.Unauthorized:
                            return Unauthorized();
                            
                        case HttpStatusCode.RequestTimeout:
                            return InternalServerError(); 
                            
                        default:
                            htmlResponse = await response.Content.ReadAsStringAsync();
                            break;
                    }
                }
    
                return Ok(htmlResponse);
    
            }

    Saturday, March 9, 2019 1:14 PM
  • User475983607 posted

    You are saving an entity using standard Entity Framework syntax.  There is nothing to comment on...

    Are you trying to solve a problem? If so, what is the problem?

    Saturday, March 9, 2019 1:30 PM
  • User-1104215994 posted

    I would like to insert response into a database which is created by EF code first approach. I posted the model in my first post.

    Should I consider;

    • Cancellation support
    • Proper error management
    • Memory management

    https://johnthiriet.com/efficient-api-calls/

    Saturday, March 9, 2019 1:34 PM
  • User475983607 posted

    I would like to insert response into a database which is created by EF code first approach. I posted the model in my first post.

    Should I consider;

    • Cancellation support
    • Proper error management
    • Memory management

    https://johnthiriet.com/efficient-api-calls/

    This post makes no sense.  Can you explain the problem you are trying to solve?

    Saturday, March 9, 2019 1:48 PM
  • User-1104215994 posted

    I didn't say there is a problem. I said I couldn't test it so I wonder if this is practically/logically OK. No big deal.

    Saturday, March 9, 2019 2:08 PM
  • User475983607 posted

    I didn't say there is a problem. I said I couldn't test it so I wonder if this is practically/logically OK. No big deal.

    If you are looking for a code or design review, then I recommend dropping the whole approach and implement a reverse proxy. 

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

    Saturday, March 9, 2019 2:19 PM