【问题标题】:Ajax api call to Web api core对 Web api 核心的 Ajax api 调用
【发布时间】:2020-07-07 14:02:14
【问题描述】:

我使用 asp.net 核心创建了一个 Web API 身份验证方法。但是从 razor 页面调用返回 400 状态代码。下面是ajax请求 $("#btLogin").on('点击', 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 () {

            }
        });      
    });

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

【问题讨论】:

  • 我无法重现您的问题。您能分享您的整个剃须刀页面和 Web api 操作吗?
  • 你给我的已经绰绰有余了,谢谢。

标签: asp.net-ajax asp.net-core-webapi razor-pages


【解决方案1】:

您不能使用JSONP 发布。它根本不起作用,它会创建一个<script> 元素来获取必须是GET 请求的数据。

这是一个工作演示:

对于 Razor 页面:

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

结果:

【讨论】:

  • services.AddMvc();在我的配置中不允许,所以我添加了 services.AddMvc(option => option.EnableEndpointRouting = false);在配置服务上可以吗?
  • 我的 ajax 成功函数没有使用相同的代码触发,我可以知道为什么吗?
  • 从您的描述看来,您的 web api 项目使用的是 asp.net core 3.x,对吧?
猜你喜欢
  • 2020-01-24
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 2019-10-25
  • 2019-05-03
  • 1970-01-01
  • 2015-03-12
  • 2016-07-14
相关资源
最近更新 更多