-1

I am trying a webapi which will support both GET and POST but the POST method needs to pass an alphanumeric parameter BUT GET should ignore any parameters.

        [HttpPost]
        [HttpGet]
        [Route("payment")]
        public virtual async Task<HttpResponseMessage> PaymentBase([FromBody] string hostOtp)
        {
            return await ((IApiPaymentController)this).Payment(hostOtp);
        }

I tried ,

  • PaymentBase([FromBody] string hostOtp) and
  • PaymentBase([FromBody] string hostOtp="")
  • PaymentBase(string hostOtp="")

with this approach PaymentBase(string hostOtp="") GET works fine,but with POST hostOtp is never getting binded.

This is the postman code,

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "http://localhost:5094/api/payment/Payment",
  "method": "POST",
  "headers": {
    "securitytoken": "0WnIxDep1knex1P13FmTWFKmIOBhgyc",
    "content-type": "application/x-www-form-urlencoded",
    "cache-control": "no-cache",
    "postman-token": "123d6825-c723-732d-737c-1964dd8f271f"
  },
  "data": {
    "hostOtp": "eqweef"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

while firing from postman with [FromBody] string hostOtp getting error,

"No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'application/octet-stream'."

sajanyamaha
  • 3,119
  • 2
  • 26
  • 44

1 Answers1

0

As you are Posting primitive type in the request body, you will need to wrap the string value in double quotes in your post

"data": '"eqweef"'

Or if the value coming from a variable

"data": '"' + hostOtp + '"'

Also, you need to explicitly declare that parameter is coming in the request body using [FromBody] and I see you did that.

[FromBody] string hostOtp
ElasticCode
  • 7,311
  • 2
  • 34
  • 45