Ajax API调用Web API核心 [英] Ajax api call to Web api core
问题描述
我已经使用asp.net核心创建了一个Web API身份验证方法.但是从剃须刀页面调用时返回400状态代码.以下是ajax请求$(#btLogin").on('click',function(){
I have created a web API authenticate method using asp.net core. But while calling from razor page returning 400 status code. below are ajax request $("#btLogin").on('click', function () {
$.ajax({
crossDomain: true,
dataType: 'jsonp',
url: 'https://localhost:xxxx/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) {
sessionStorage.setItem('userName', resp.User_nm);
sessionStorage.setItem('accessToken', resp.tokenString);
authHeaders.Authorization = 'Bearer ' + resp.tokenString;
location.href = "https://localhost:xxx/Home";
},
error: function () {
}
});
});
我可以知道里面有什么问题吗?
May I know what is wrong in it ?
推荐答案
您不能使用 JSONP
进行POST.这根本行不通,它会创建< script>
元素以获取必须是GET请求的数据.
You can't POST using JSONP
.It simply doesn't work that way, it creates a <script>
element to fetch data which has to be a GET request.
这是一个工作示例:
对于Razor Pages:
Index.cshtml:
Index.cshtml:
@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...
}
}
请确保将您的Web api项目配置为启用启用跨域请求(CORS):
Be sure to configure your web api project to enable enable Cross-Origin Requests (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();
}
结果:
这篇关于Ajax API调用Web API核心的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!