0

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?

1 Answer 1

3

Please modify the url and Content-Type like below.

JS client

var data = JSON.stringify({
    Username: this.username,
    Email: this.email,
    Password: this.password
});


this.$axios.post('http://localhost:54166/api/register', data
, {
    headers: {
    'Content-Type': 'application/json'
    }
}
).then(function (response) {
console.log(response)
})
.catch(function (error) {
    console.log(error)
})

Controller action

[HttpPost]
public async Task<string> Post([FromBody]RegisterModel m)
{

    //code logic here
}

Test result

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I feel quite stupid. I'd forgotten to add api/ before the controller target in the link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.