【发布时间】:2020-04-15 04:44:06
【问题描述】:
我想从 Javascript Axios 向我的 Asp.Net Core 3.1 Web API 发送一个对象,虽然看起来请求正在发送,但服务器没有接收到它。
[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; }
}
我已经启用了 Cors,或者至少我认为我已经启用了:
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);
});
}
这是我的 Javascript 代码:
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)
})
}
上面我尝试发送一个简单的字符串请求,但即使这样也没有被接收到。 有人知道为什么这不起作用吗?
【问题讨论】:
标签: javascript rest asp.net-core asp.net-web-api axios