I want to send an object from Javascript Axios to my Asp.Net Core 3.1 web API and although it seems like the request is being sent, the server isn't picking it up.
[EnableCors("AllowAllOrigins")]
[Route("api/[controller]")]
[ApiController]
public class RegisterController : ControllerBase
{
[HttpPost]
public async Task<string> Post([FromBody]string m)
{
//RegisterModel m = JsonConvert.DeserializeObject<RegisterModel>(data);
//if(string.IsNullOrEmpty(m.Username) == false && string.IsNullOrEmpty(m.Password) == false && string.IsNullOrEmpty(m.Email) == false )
//{
// Debug.WriteLine(m.Username);
// Debug.WriteLine(m.Password);
// Debug.WriteLine(m.Email);
// return "Ok";
//}
//return "Bad";
Debug.WriteLine(m);
return m;
}
}
public class RegisterModel
{
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
}
I've enabled Cors or at least I think I did:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSignalR().AddJsonProtocol(options => {
options.PayloadSerializerOptions.PropertyNamingPolicy = null;
});
services.Configure<IISServerOptions>(options =>
{
options.AutomaticAuthentication = false;
});
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin());
});
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args);
// 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();
}
if (env.IsProduction())
{
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<ControlHub>("/controlhub");
});
app.UseCors("AllowAllOrigins");
app.Use(async (context, next) =>
{
var hubContext = context.RequestServices
.GetRequiredService<IHubContext<ControlHub>>();
TelegramBot bot = new TelegramBot();
bot.Start(hubContext);
});
}
And here is my Javascript Code:
methods: {
Register () {
// var data = JSON.stringify({
// Username: this.username,
// Email: this.email,
// Password: this.password
// })
var data2 = 'Hello'
this.$axios.post('http://localhost:54166/register', data2
, {
headers: {
'Content-Type': 'text/plain'
}
}
).then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
Above I've tried to send a simple string request but even this isn't getting picked up. Anybody has any idea of why this isn't working?
