All,
I am getting the following exception when I try call my web api (.net 6) end point using postman (I tried content type: form-data/application/x-www-form-urlencoded and I did include user, pwd parameters in the body, post url: http://localhost:5000/api/auth):
{StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
Date: Thu, 17 Mar 2022 18:12:40 GMT
Server: Kestrel
Transfer-Encoding: chunked
Content-Type: application/problem json; charset=utf-8
}}
Here's my web api controller:
[ApiController]
[Route("/api/[controller]")]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
public AuthController(ILogger<AuthController> logger)
{
_logger = logger;
}
[HttpPost()]
public string GetToken([FromBody] AuthCredentials cred)
{
_logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
_logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
return "token:12345";
}
}
It worked before, when I was passing user/pwd as separate fields, the minute I put [FromBody] it stopped working and I started getting this exception.
public class AuthCredentials
{
public string User { get; set; }
public string Pwd { get; set; }
}
I do use SignalR Webapis, here's my Startup.cs
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(); // only for web api controllers
services.AddSignalR()
.AddHubOptions<ServerHub>(options =>
{
options.EnableDetailedErrors = true;
options.MaximumReceiveMessageSize = null; // null is unlimited
})
// add message pack, requires nuget: Microsoft.AspNetCore.SignalR.Protocols.MessagePack (you must be on .net6 to use this nuget)
.AddMessagePackProtocol();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Running SignalR hub, at url: /server");
});
endpoints.MapHub<ServerHub>("/server", options =>
{
options.Transports = HttpTransportType.WebSockets;
});
endpoints.MapControllers(); // only for api controllers
});
}
}
**
- UPDATE: Fixed the Unsupported Media Type
** I was able to fix the Unsupported Media Type exception by changing this line and adding form data content-type:
services
.AddControllers(options =>
{
var jsonInputFormatter = options.InputFormatters
.OfType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>()
.Single();
jsonInputFormatter.SupportedMediaTypes
.Add("application/x-www-form-urlencoded");
});
But now, when I run post man I get 400, bad request exception:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-46970e65eec389a5d6d355d960823e57-dd8db1776ac7f90c-00",
"errors": {
"$": [
"The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
]
}
}
Q: How can I pass in using form Data (user, pwd), and populate AuthCredentials object on the server?
CodePudding user response:
if you trying to call this action from postman
[HttpPost()]
public string GetToken([FromBody] AuthCredentials cred)
_logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
_logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
return "token:12345";
}
you need to select body=>raw=>json options in postmant and add your data as
{
"user": "user",
"pwd" : "pwd"
}
and remove all extra code you added to AddController config. It is only confusing and probably will cause more problems in the future
CodePudding user response:
The reason why it's doesn't work, is that you are trying to retrieve parameter from the URL, but you are using [FromBody] which is supposed to use the body of your request to send parameters .
Try to send your parameters as shown below