Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error unexpected character encountered while parsing value: . Path '', line 1, position 1

I have an ASP.Net Core 2.1 app. I am getting the same error as mentioned in the below SO link.

Unexpected character encountered while parsing value: . Path '', line 1, position 1

The solution suggested in the answer section seems to solve the issue as well.

But creating a class for one property is overhead & doesn't appeal to me.

In the past, I did the same without creating such overhead class with .Net Framework 4.5(+)

// POST api/values
[HttpPost]
public void Post([FromBody]string email)
{
}

Through Postman, I POST

{
    "email": "[email protected]"
}

How can I pass the email value to API without creating any class or such?

I would prefer to stick [FromBody], as all the APIs in my application is accepting the params FromBody in Post method.

like image 237
Kgn-web Avatar asked Sep 13 '19 08:09

Kgn-web


2 Answers

If you want to pass the email value without creating class, just pass

"[email protected]"

without the {} brackets and the email key. When you pass

{
"email": "[email protected]"
}

the parser correctly suggests that this value represents object with property email, that is why wrapper class is needed.

like image 105
Marmellad Avatar answered Nov 08 '22 05:11

Marmellad


If you know you're only ever going to need one argument, then go ahead and make it a string, as others have suggested. But please remember that you will not be able to receive two arguments from the body in ASP.NET Core: you will have to define a type that contains two (or more) properties, and the single object in the request body will be mapped to that type. So, if you're not sure, just save yourself the future refactoring and define a type for your request.

Don't be afraid of creating one more class in your project. It is a very small overhead for the machine, and a minuscule annoyance for you to spend three minutes writing it, but it improves the quality of your code, makes it more expressive, and it can even help you by making the compiler find mistakes you may not have noticed. Just give it a meaningful name, and you'll be fine.

like image 2
Simone Avatar answered Nov 08 '22 04:11

Simone