Ajax api 调用 Web api 核心

Ajax api call to Web api core

我使用 asp.net 核心创建了一个网络 API 身份验证方法。但是从剃刀页面调用时返回 400 状态代码。以下是 ajax 个请求 $("#btLogin").on('click', 函数 () {

        $.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 () {

            }
        });      
    });

我可以知道它有什么问题吗?

您不能 POST 使用 JSONP。它根本无法那样工作,它会创建一个 <script> 元素来获取必须是 GET 请求的数据。

这是一个工作演示:

对于 Razor 页面:

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>
}

网络版 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):

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();
}

结果: