locked
How to get JSON request and POST it to another Api? RRS feed

  • Question

  • User-1104215994 posted

    Hello;

    I created a web <g class="gr_ gr_27 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="27" data-gr-id="27">api</g> project and here is my controller below. I am trying to make postman POST request call to this controller which has x-www-form-<g class="gr_ gr_169 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="169" data-gr-id="169">urlencoded</g> values in the body.

    [RoutePrefix("api/v1/pin")]
        public class GameController : ApiController
        {
            
            // POST: api/Game
            [HttpPost, Route("initiation")]
            public async System.Threading.Tasks.Task PurchaseInitiationAsync([FromBody]string value)
            {
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(value);
                HttpResponseMessage response =
                    await httpClient.PostAsync("https://test.game.com/purchaseinitiation", content);
                string statusCode = response.StatusCode.ToString();
                
            }
    
            
        }

    I would like to get this JSON request body and make another call to URI. But content is NULL. How can I achieve to send JSON to the URI?

    Best Regards.

    Monday, February 4, 2019 2:01 PM

Answers

  • User-474980206 posted
              
    HttpClient httpClient = new HttpClient();
    HttpContent content = new StringContent(
       JsonConvert.SerializeObject(value),
       Encoding.UTF8,
       "application/json"
    );
    HttpResponseMessage response = await httpClient
        .PostAsync("https://test.game.com/purchaseinitiation", content);
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 4, 2019 5:52 PM
  • User475983607 posted

    cenk1536

    Simply there is a rest API host and a client. I am trying to implement a rest API is in the middle of them. My api is like transporter. Client makes request to my api, I am transfering the request to other api host. Than return the response from host to the client.

    Basically, you'll have a matching endpoint for each of the "other api host".

    First, craft a .NET object (POCO) that models the expected JOSN result.

        public class ProductPoco
        {
            public string ReferenceId { get; set; }
            public string ProductCode { get; set; }
            public string Quantity { get; set; }
            public string InitiationResultCode { get; set; }
            public string ValidatedToken { get; set; }
            public string Version { get; set; }
            public string Signature { get; set; }
            public string ApplicationCode { get; set; }
        }

    Your service that invokes the other service will look similar to the following.

            [HttpPost]
            public async Task<ProductPoco> Post(string value)
            {
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
    
                HttpResponseMessage response = await httpClient.PostAsync("https://localhost:44381/api/default", content);
               return await response.Content.ReadAsAsync<ProductPoco>();
    
            }

    Below is the 44381 test service that populates the POCO.

            [HttpPost]
            public ProductPoco Post(string value)
            {
                return new ProductPoco()
                {
                    ReferenceId = "28944118272",
                    ProductCode = "001002461285",
                    Quantity = "1",
                    InitiationResultCode = "04",
                    ValidatedToken = "",
                    Version = "V1",
                    Signature = "c8ab4",
                    ApplicationCode = "52e7cf9"
                };
            }

    Finally, the PostMan configuration.

    • URL: https://localhost:44326/api/default
    • Action: POST
    • content-type: application/json
    • Body: "test"

    PostMan results.

    {
        "referenceId": "28944118272",
        "productCode": "001002461285",
        "quantity": "1",
        "initiationResultCode": "04",
        "validatedToken": "",
        "version": "V1",
        "signature": "c8ab4",
        "applicationCode": "52e7cf9"
    }

    In the example above, the input parameter does nothing.  I assume the input is also a complex type.  In which case you should craft a proper model .NET model.   

    Also the example above is in no way production code.  The example does not handle the HttpClient properly which can lead to connection exhaustion.  There's no error handling.

    If you are trying to build a proxy then you are going about this the wrong way, IMHO.  I'm pretty sure we've been down this road in your other threads.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 4, 2019 8:16 PM

All replies

  • User475983607 posted

    Hello;

    I created a web api project and here is my controller below. I am trying to make postman POST request call to this controller which has x-www-form-urlencoded values in the body.

    [RoutePrefix("api/v1/pin")]
        public class GameController : ApiController
        {
            
            // POST: api/Game
            [HttpPost, Route("initiation")]
            public async System.Threading.Tasks.Task PurchaseInitiationAsync([FromBody]string value)
            {
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(value);
                HttpResponseMessage response =
                    await httpClient.PostAsync("https://test.game.com/purchaseinitiation", content);
                string statusCode = response.StatusCode.ToString();
                
            }
    
            
        }

    I would like to get this JSON request body and make another call to URI. But content is NULL. How can I achieve to send JSON to the URI?

    Best Regards.

    What is null?

    Monday, February 4, 2019 2:44 PM
  • User-1104215994 posted

    content;

    HttpContent content = new StringContent(value);

    Monday, February 4, 2019 2:48 PM
  • User475983607 posted

    content;

    HttpContent content = new StringContent(value);

    That indicates the code that calls the PurchaseInitiationAsync() method has problem.  We cannot see this code...

    Please take a moment to review your code and do a little troubleshooting.

    Monday, February 4, 2019 3:24 PM
  • User-1104215994 posted

    There is no code calling the PurchaseInitiationAsync(). I am calling from POSTMAN. There is no error because I am sending request with the same parameteres to directly the URI.

    Monday, February 4, 2019 4:51 PM
  • User-474980206 posted
              
    HttpClient httpClient = new HttpClient();
    HttpContent content = new StringContent(
       JsonConvert.SerializeObject(value),
       Encoding.UTF8,
       "application/json"
    );
    HttpResponseMessage response = await httpClient
        .PostAsync("https://test.game.com/purchaseinitiation", content);
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 4, 2019 5:52 PM
  • User475983607 posted

    There is no code calling the PurchaseInitiationAsync(). I am calling from POSTMAN. There is no error because I am sending request with the same parameteres to directly the URI.

    PostMan is a client!   Provide the PostMan configuration.

    Monday, February 4, 2019 6:14 PM
  • User-1104215994 posted

    Thank you <g class="gr_ gr_7 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="7" data-gr-id="7">bruce</g>. How can I return the <g class="gr_ gr_42 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="42" data-gr-id="42">respose</g> back to POSTMAN?

    public class GameController : ApiController
        {
            
            // POST: api/Game
            [HttpPost, Route("initiation")]
            public async System.Threading.Tasks.Task PurchaseInitiationAsync([FromBody]string value)
            {
    
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
                
    
                //HttpContent content = new StringContent(value);
                HttpResponseMessage response =
                    await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
                string statusCode = response.StatusCode.ToString();
                
                
            }
    
            
        }

    Monday, February 4, 2019 6:15 PM
  • User475983607 posted

    You have not provided the return type only task.  What is the return type?

    Monday, February 4, 2019 6:19 PM
  • User-1104215994 posted

    <g class="gr_ gr_13 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="13" data-gr-id="13">JSON</g> response is the return type.

    Monday, February 4, 2019 6:21 PM
  • User475983607 posted

    JSON response is the return type.

    Post the expected JSON format if you do not know the type.

    Monday, February 4, 2019 6:24 PM
  • User-1104215994 posted

    Is this the POSTMAN's JSON request? I don't think so.

    [FromBody]string value
    HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
    {
        "Headers": [
            {
                "Key": "Content-Type",
                "Value": [
                    "application/json; charset=utf-8"
                ]
            },
            {
                "Key": "Content-Length",
                "Value": [
                    "4"
                ]
            }
        ]
    }

    when I print out the HTTPContent; I am getting Headers. It is not the JSON request.

    Monday, February 4, 2019 7:08 PM
  • User475983607 posted

    Generally, when you send an HTTP request to a REST endpoint you know what to expect in return.  If you do not know what to expect then how do you know if the result is an JSON formatted error or even another format like HTML?

    It is certifiably possible to read the API response from HttpClient as a string then populate a generic JSON response but that's a bit risky for the same reason as above.

    Can you explain at a high level what you are trying to do?

    By the way, the response is in the HTTP body not the HTTP headers.

    Monday, February 4, 2019 7:27 PM
  • User-1104215994 posted

    I am expecting to get this JSON:

    "{\"referenceId\":\"28944118272\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"initiationResultCode\":\"04\",\"validatedToken\":\"\",\"version\":\"V1\",\"signature\":\"c8ab4\",\"applicationCode\":\"52e7cf9\"}"

    If I directly call the URI from POSTMAN, I am getting the above JSON. But if I call my code above from POSTMAN, I am getting below;

    {
        "Headers": [
            {
                "Key": "Content-Type",
                "Value": [
                    "application/json; charset=utf-8"
                ]
            },
            {
                "Key": "Content-Length",
                "Value": [
                    "4"
                ]
            }
        ]
    }

    Simply there is a rest API host and a client. I am trying to implement a rest API is in the middle of them. My <g class="gr_ gr_501 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="501" data-gr-id="501">api</g> is like <g class="gr_ gr_561 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="561" data-gr-id="561">transporter</g>. <g class="gr_ gr_672 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="672" data-gr-id="672">Client</g> makes <g class="gr_ gr_673 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="673" data-gr-id="673">request</g> to my <g class="gr_ gr_669 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="669" data-gr-id="669">api</g>, I am <g class="gr_ gr_712 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="712" data-gr-id="712">transfering</g> the request to <g class="gr_ gr_816 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar multiReplace" id="816" data-gr-id="816">other <g class="gr_ gr_785 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="785" data-gr-id="785">api</g> host</g>. <g class="gr_ gr_898 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="898" data-gr-id="898">Than</g> return the response from host to the client.

    Monday, February 4, 2019 7:35 PM
  • User475983607 posted

    cenk1536

    Simply there is a rest API host and a client. I am trying to implement a rest API is in the middle of them. My api is like transporter. Client makes request to my api, I am transfering the request to other api host. Than return the response from host to the client.

    Basically, you'll have a matching endpoint for each of the "other api host".

    First, craft a .NET object (POCO) that models the expected JOSN result.

        public class ProductPoco
        {
            public string ReferenceId { get; set; }
            public string ProductCode { get; set; }
            public string Quantity { get; set; }
            public string InitiationResultCode { get; set; }
            public string ValidatedToken { get; set; }
            public string Version { get; set; }
            public string Signature { get; set; }
            public string ApplicationCode { get; set; }
        }

    Your service that invokes the other service will look similar to the following.

            [HttpPost]
            public async Task<ProductPoco> Post(string value)
            {
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
    
                HttpResponseMessage response = await httpClient.PostAsync("https://localhost:44381/api/default", content);
               return await response.Content.ReadAsAsync<ProductPoco>();
    
            }

    Below is the 44381 test service that populates the POCO.

            [HttpPost]
            public ProductPoco Post(string value)
            {
                return new ProductPoco()
                {
                    ReferenceId = "28944118272",
                    ProductCode = "001002461285",
                    Quantity = "1",
                    InitiationResultCode = "04",
                    ValidatedToken = "",
                    Version = "V1",
                    Signature = "c8ab4",
                    ApplicationCode = "52e7cf9"
                };
            }

    Finally, the PostMan configuration.

    • URL: https://localhost:44326/api/default
    • Action: POST
    • content-type: application/json
    • Body: "test"

    PostMan results.

    {
        "referenceId": "28944118272",
        "productCode": "001002461285",
        "quantity": "1",
        "initiationResultCode": "04",
        "validatedToken": "",
        "version": "V1",
        "signature": "c8ab4",
        "applicationCode": "52e7cf9"
    }

    In the example above, the input parameter does nothing.  I assume the input is also a complex type.  In which case you should craft a proper model .NET model.   

    Also the example above is in no way production code.  The example does not handle the HttpClient properly which can lead to connection exhaustion.  There's no error handling.

    If you are trying to build a proxy then you are going about this the wrong way, IMHO.  I'm pretty sure we've been down this road in your other threads.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, February 4, 2019 8:16 PM
  • User-1104215994 posted

    Let me put it this way, I have implemented this proxy in python flask. I decided to implement in web <g class="gr_ gr_18 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="18" data-gr-id="18">api</g> because it is really really hard to deploy flask on windows IIS. (I have to use IIS due to hardware restrictions and maintenance)

    So my flask application is working as it is planned. Client (which is Postman ta this time) sends a similar JSON request to my proxy as follows;

    {
        "referenceId": "70000600007",
        "productCode": "001002461285",
        "quantity": "1",
        "version": "V1",
        "signature": "fd96fc3",
        "applicationCode": "52e7cf96"
    }

    My proxy sends this request to the host and host returns back <g class="gr_ gr_21 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="21" data-gr-id="21">similar</g> response to my app than I send back to <g class="gr_ gr_22 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="22" data-gr-id="22">client</g>.

    "{\"referenceId\":\"28944118272\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"initiationResultCode\":\"04\",\"validatedToken\":\"\",\"version\":\"V1\",\"signature\":\"c8ab4f1e\",\"applicationCode\":\"52e7cf966b\"}"

    I wonder why wouldn't I send back the response JSON to the client (here is POSTMAN) if I don't use Poco as you described in your post? Should I need to create POCO (model) in order to send <g class="gr_ gr_16 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="16" data-gr-id="16">response</g>?

    Bytheway, I am sending parameters in <g class="gr_ gr_15 gr-alert gr_gramm gr_hide gr_inline_cards gr_run_anim Style multiReplace replaceWithoutSep replaceWithoutSep" id="15" data-gr-id="15"><g class="gr_ gr_14 gr-alert gr_gramm gr_hide gr_inline_cards gr_run_anim Grammar only-ins multiReplace replaceWithoutSep gr-progress" id="14" data-gr-id="14">x-www-form-<g class="gr_ gr_13 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="13" data-gr-id="13">urlencoded</g></g>  format</g> in POSTMAN body.

    As you described I implemented Initiate model and now value parameter for PurchaseInitiationAsync is NOT NULL.

    // POST: api/Game
            [HttpPost, Route("initiation")]
            public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
            {
                
                HttpClient httpClient = new HttpClient();
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
                
    
               
                HttpResponseMessage response =
                    await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
    
                
                return await response.Content.ReadAsAsync<Initiate>();
            }
    

    Tuesday, February 5, 2019 5:18 AM
  • User475983607 posted

    Should I need to create POCO (model) in order to send response?

    You can build and return an HttpResponse by hand rather than letting the framework do the hard work.

    Bytheway, I am sending parameters in x-www-form-urlencoded  format in POSTMAN body.

    I asked for this information two times above...

    I recommend learning HTTP basics.

    Tuesday, February 5, 2019 12:35 PM
  • User-1104215994 posted

    Hi <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="5" data-gr-id="5">mgehard</g>;

    I am getting this error. Could you please help?

    "Message": "An error has occurred.",
    "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Initiate' from content with media type 'text/html'.",
    "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",

    public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
            {
    
                if (value == null)
                {
                    var message = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(string.Format("Request is NULL! Please check your data.")),  
                        ReasonPhrase = "Request is NULL! Please check your data."
                    };
    
                    throw new HttpResponseException(message);
                }
    
                HttpClient httpClient = new HttpClient();
                
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
                
    
               
                HttpResponseMessage response =
                    await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
    
                
                return await response.Content.ReadAsAsync<Initiate>();
            }

    Tuesday, February 5, 2019 6:47 PM
  • User475983607 posted

    cenk1536

    Hi mgehard;

    I am getting this error. Could you please help?

    "Message": "An error has occurred.",
    "ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'Initiate' from content with media type 'text/html'.",
    "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",

    public async System.Threading.Tasks.Task<Initiate> PurchaseInitiationAsync([FromBody]Initiate value)
            {
    
                if (value == null)
                {
                    var message = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(string.Format("Request is NULL! Please check your data.")),  
                        ReasonPhrase = "Request is NULL! Please check your data."
                    };
    
                    throw new HttpResponseException(message);
                }
    
                HttpClient httpClient = new HttpClient();
                
                HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );
                
    
               
                HttpResponseMessage response =
                    await httpClient.PostAsync("http://test:1907/purchase_initiation", content);
    
                
                return await response.Content.ReadAsAsync<Initiate>();
            }

    Sorry, don't have my crystal ball handy.  My best guesses are, either the client calling PurchaseInitiationAsync() has issues or the HttpClient request triggered an exception where an HTML response, probably an HTML error message, returned from http://test:1907/purchase_initiation.

    Tuesday, February 5, 2019 7:02 PM
  • User-1104215994 posted

    The client is Postman which has header content-type application/<g class="gr_ gr_9 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="9" data-gr-id="9">json</g>. <g class="gr_ gr_6 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="6" data-gr-id="6">Json</g> data is x-www-form-<g class="gr_ gr_10 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="10" data-gr-id="10">urlencoded</g>. 

    I added JsonMediaTypeFormatter as follows but couldn't fix the error.

    var obj = response.Content.ReadAsAsync<Initiate>(
                    new List<MediaTypeFormatter>
                    {
                        new JsonMediaTypeFormatter()
                    }).Result;
    
                return obj;

    Tuesday, February 5, 2019 7:13 PM
  • User-1104215994 posted

    I think registering JSONMediaTypeFormatter in WebApiCongif will solve this issue.

    public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
                config.Formatters.Add(new JsonMediaTypeFormatter());

    Wednesday, February 6, 2019 5:45 AM
  • User-1104215994 posted

    Unfortunately didn't work.

    Wednesday, February 6, 2019 4:52 PM
  • User475983607 posted

    You have not provided enough information to guess where the bug is located.  See my previous post for possible errors.  Usually the error message tells which line of code...

    Wednesday, February 6, 2019 5:04 PM
  • User-1104215994 posted

    Body of postman:

    Error I am receiving:

    <{"Message":"An error has occurred.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Initiate' from content with media type 'text/html'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" konum: System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n konum: System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger)\r\n konum: System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, IEnumerable`1 formatters)\r\n konum: EPINMiddleWareAPI.Controllers.GameController.<PurchaseInitiationAsync>d__0.MoveNext() C:\\Users\\197199\\Documents\\Visual Studio 2017\\Projects\\EPINMiddleWareAPI\\EPINMiddleWareAPI\\Controllers\\GameController.cs içinde: satır 50\r\n--- Özel durumun oluşturulduğu önceki konumdan başlayan yığın izlemesinin sonu ---\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n konum: System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- Özel durumun oluşturulduğu önceki konumdan başlayan yığın izlemesinin sonu ---\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n konum: System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- Özel durumun oluşturulduğu önceki konumdan başlayan yığın izlemesinin sonu ---\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n konum: System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- Özel durumun oluşturulduğu önceki konumdan başlayan yığın izlemesinin sonu ---\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n konum: System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n konum: System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"}>

    seems that error is due to this line;

    return await response.Content.ReadAsAsync<Initiate>();

    here is postman console:

    Request Headers:
    Content-Type:"application/x-www-form-urlencoded"
    cache-control:"no-cache"
    Postman-Token:"bbaa8370-bf3c-42a4-b10b-aff07b862885"
    User-Agent:"PostmanRuntime/7.6.0"
    Host:"localhost:61217"
    accept-encoding:"gzip, deflate"
    content-length:192
    Request Body:
    ApplicationCode:"52e7cf966b724749a7c4efadc3727ed7"
    productCode:"001002461285"
    quantity:"1"
    referenceId:"28944118272"
    version:"V1"
    signature:"73b36a52ad3b0c85dc6b1a8a536e75bf"
    merchantProductCode:"113131231"
    Response Headers:
    Cache-Control:"no-cache"
    Pragma:"no-cache"
    Content-Type:"application/json; charset=utf-8"
    Expires:"-1"
    Server:"Microsoft-IIS/10.0"
    X-AspNet-Version:"4.0.30319"
    X-SourceFiles:"=?UTF-8?B?QzpcVXNlcnNcMTk3MTk5XERvY3VtZW50c1xWaXN1YWwgU3R1ZGlvIDIwMTdcUHJvamVjdHNcRVBJTk1pZGRsZVdhcmVBUElcRVBJTk1pZGRsZVdhcmVBUElcYXBpXHYxXHBpblxpbml0aWF0aW9u?="
    X-Powered-By:"ASP.NET"
    Date:"Wed, 06 Feb 2019 17:38:22 GMT"
    Content-Length:"2583"

    Wednesday, February 6, 2019 5:29 PM
  • User475983607 posted

    As clearly stated above... The response is HTML (text/html) but you are trying to deserialize the response as application/json.   More than likely the HTML response is an error message with all the details.  All you have to do is read the error message.  

    Wednesday, February 6, 2019 6:26 PM
  • User-1104215994 posted

    I added JsonMediaTypeFormatter to response but still got the same error. I don't understand.

    var obj = response.Content.ReadAsAsync<Initiate>(
                    new List<MediaTypeFormatter>
                    {
                        new JsonMediaTypeFormatter()
                    }).Result;
    
                return obj;

    Wednesday, February 6, 2019 6:34 PM
  • User475983607 posted

    I added JsonMediaTypeFormatter to response but still got the same error. I don't understand.

    var obj = response.Content.ReadAsAsync<Initiate>(
                    new List<MediaTypeFormatter>
                    {
                        new JsonMediaTypeFormatter()
                    }).Result;
    
                return obj;

    Your response to this issue makes no logical sense.   I recommend spending a lot more time learning REST, HTTP, and serialization basics before moving forward. 

    The issue - according to your comments - is this service...

    https://test.game.com/purchaseinitiation

    is returning an HTML content-type response not the expected JSON content-type.  Usually when this happens the HTML contains an error message.  Again, take a moment to read the response message then you should be able to figure out what to do next. 

    You'll need to change the code a bit to get the message. 

    string htmlResponse = await response.Content.ReadAsStringAsync();

    Wednesday, February 6, 2019 6:47 PM
  • User-1104215994 posted

    thank you, now we are getting somewhere. How can I see the contents of <g class="gr_ gr_54 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins replaceWithoutSep" id="54" data-gr-id="54">content</g>?

    HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );

    Wednesday, February 6, 2019 6:55 PM
  • User475983607 posted

    thank you, now we are getting somewhere. How can I see the contents of content?

    HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );

    Set a breakpoint and use the locals windows to drill into the object.  You're submitting the "value" variable so it's strange that you do not know what you're sending. 

    Wednesday, February 6, 2019 9:07 PM
  • User-1104215994 posted

    How genius :) When debugging, it writes content byte[238]. I can't see my data. <g class="gr_ gr_65 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="65" data-gr-id="65">However</g> there is data that I send in value. I make them bold, is it clear?

    HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );

    Thursday, February 7, 2019 5:10 AM
  • User475983607 posted

    How genius :) When debugging, it writes content byte[238]. I can't see my data. However there is data that I send in value. I make them bold, is it clear?

    HttpContent content = new StringContent(
                    JsonConvert.SerializeObject(value),
                    Encoding.UTF8,
                    "application/json"
                );

    This is very basic stuff.   You had to type parameters into the body of the PostMan View.  Show the parameters.  Also show the this new class; Initiate.

    There is no logical reason that you need to see the HttpContext but you can and it does show the everything you need.  I'm not sure why you are unable to navigate the debugger. But all you have to do is...

    string json = JsonConvert.SerializeObject(value);

    ... to see the string.  By the way this can be done in the debugger;s immediate window.

    Thursday, February 7, 2019 11:37 AM
  • User-1104215994 posted

    Oh boy :) I found out why this error occurs. The body x-www-form-<g class="gr_ gr_72 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace replaceWithoutSep" id="72" data-gr-id="72">urlencodedparameters</g> starts with lower case (referenceId, productCode...etc) But <g class="gr_ gr_143 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del" id="143" data-gr-id="143">some how</g> my code makes them all uppercase. How could this happen?

    {"ReferenceId":"28944118272","ProductCode":"001002461285","Quantity":"1","InitiationResultCode":null,"ValidatedToken":null,"Version":"V1","Signature":"73b36a52ad3b0c85dc6b1a8a536e75bf","ApplicationCode":"52e7cf966b724749a7c4efadc3727ed7"}

    Thursday, February 7, 2019 5:17 PM
  • User-1104215994 posted

    damn model :)

    Thursday, February 7, 2019 5:43 PM