Вы не можете POST использовать JSONP
. Это просто не работает таким образом, он создает элемент <script>
для извлечения данных, который должен быть запросом GET.
Вот рабочая демонстрация:
Для страниц бритвы:
Index.cs html:
@page
@model IndexModel
@{
ViewData["Title"] = "Home page";
}
<form>
<div>
<input id="txtUserName" />
</div>
<div>
<input id="txtPassword" />
</div>
<div>
<input type="button" id="btLogin" value="login" />
</div>
</form>
@section Scripts
{
<script>
$("#btLogin").on('click', function () {
$.ajax({
crossDomain: true,
//dataType: 'jsonp',
url: 'https://localhost:44338/api/users/authenticate',
type: "POST",
//headers: { 'Access-Control-Allow-Origin': '*' },
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: ({
username: $("#txtUserName").val(),
password: $("#txtPassword").val()
}),
success: function (resp) {
//...
},
error: function () {
}
});
});
</script>
}
Для Web Api:
Модель:
public class Login
{
public string Username { get; set; }
public string Password { get; set; }
}
Контроллер:
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
[HttpPost("Authenticate")]
public IActionResult Authenticate([FromForm]Login user)
{
//do your stuff...
}
}
Обязательно настройте проект веб-API для включения Cross -Оригинальные запросы (CORS):
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(
options => options.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
);
//...
app.UseMvc();
}
Результат: ![enter image description here](https://i.stack.imgur.com/aD5fe.gif)