Ajax API вызов к ядру Web API - PullRequest
0 голосов
/ 26 марта 2020

Я создал метод аутентификации веб-API с использованием ядра asp. net. Но при звонке со страницы бритвы возвращается 400 кодов статуса. ниже 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 () {

            }
        });      
    });

Могу ли я узнать, что в нем не так?

1 Ответ

0 голосов
/ 27 марта 2020

Вы не можете 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

...