Reputation: 151
I send a parameter in axios to api and I run linq to get the result.
Unfortunately when it comes to a function in api I get the value null
Where am I wrong?
the code:
react:
const code= "sdasdasdadad"
axios.post('api/UserDetails/', code).then((response) => setUserDetails(response.data));
C#:
[Microsoft.AspNetCore.Mvc.Route("UserDetails")]
[Microsoft.AspNetCore.Mvc.HttpPost]
public Users UserDetails(string code)
{
try
{
return _context.User.Where(x=>x.Code==code).FirstOrDefault();
}
catch (Exception)
{
return null;
}
}
Upvotes: 0
Views: 952
Reputation: 27803
If you really want your APIs work well with plain text input, you can try to implement a custom plain text input formatter, like below.
public class TextPlainInputFormatter : TextInputFormatter
{
public TextPlainInputFormatter()
{
SupportedMediaTypes.Add("text/plain");
SupportedEncodings.Add(UTF8EncodingWithoutBOM);
SupportedEncodings.Add(UTF16EncodingLittleEndian);
}
protected override bool CanReadType(Type type)
{
return type == typeof(string);
}
public override async Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
{
string data = null;
using (var streamReader = new StreamReader(context.HttpContext.Request.Body))
{
data = await streamReader.ReadToEndAsync();
}
return InputFormatterResult.Success(data);
}
}
Configure and use custom formatter
services.AddControllers(opt => opt.InputFormatters.Insert(0, new TextPlainInputFormatter()));
API Action
[Microsoft.AspNetCore.Mvc.Route("UserDetails")]
[Microsoft.AspNetCore.Mvc.HttpPost]
public Users UserDetails([FromBody]string code)
{
//...
Make request using axios
const code = "sdasdasdadad";
const headers = {
'Content-Type': 'text/plain'
};
axios.post('api/UserDetails', code, { headers: headers }).then((response) => setUserDetails(response.data));
Test Result
Upvotes: 1