ASP.NET REST POST - JavaScript(jQuery)在POST中发送Body

时间:2017-10-31 04:00:39

标签: javascript c# jquery rest asp.net-core-webapi

当我从C#应用程序调用它时,我有一个REST调用工作正常,但是我无法让我的JavaScript页面在POST主体中发送内容。这是REST控制器。请注意,如果我删除" FromBody"来自呼叫的属性。

[Route("api/[controller]")]
public class AuthenticateController : Controller
{
    [HttpPost]
    public ActionResult Post([FromBody] CredentialsModel credentialsModel)
    {
        var authenticationModel = new AuthenticationModel { IsSuccess = false };

        if (credentialsModel != null && !string.IsNullOrEmpty(credentialsModel.Username) && !string.IsNullOrEmpty(credentialsModel.Password))
        {
            authenticationModel = SecurityBusinessLayer.IsValidUser(credentialsModel.Username, credentialsModel.Password);
        }

        var json = JsonConvert.SerializeObject(authenticationModel, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects, ReferenceLoopHandling = ReferenceLoopHandling.Serialize });

        return Content(json);
    }
}

这是使用JQuery的JavaScript:

function authenticate(username, password)
{
    //Get the authenticate api url
    var uriHref = window.location.href;
    var lastIndexOfSlash = uriHref.lastIndexOf('/');
    var apiPath = uriHref.substring(0, lastIndexOfSlash) + "/api";
    var encodedUri = encodeURI(apiPath + "/authenticate/");

    var credentials = {};
    credentials["Username"] = username;
    credentials["Password"] = password;

    //Post the username and password to the server
    $.post(encodedUri, credentials, function (data)
    {
        //Parse the returned data (should match Adapt.Data.Generic.AuthenticationModel)
        var response = JSON.parse(data);

        if (response.IsSuccess)
        {
            //Ensure the token will expire
            var expiryDate = new Date();
            expiryDate = new Date(expiryDate.setTime(expiryDate.getTime() + 86400000));

            //Set the auth token cookie
            var cookieString = "authToken=" + response.Authtoken + "; expires=" + expiryDate.toUTCString() + ";path=/";
            document.cookie = cookieString;

            //Goto the xivic app page
            window.location = "Index.html";
        }
        else
        {
            //Failed to log in, show error message
            $("#badLoginMessage").css("visibility", "visible");
        }
    });
}

2 个答案:

答案 0 :(得分:1)

当你删除[FromBody时,你必须发布Json对象而不是数组]

$.ajax({
                url: encodedUri,
                type: 'POST',
                data: {
                    Username: jsonString,Password:password
                },
                success: function (data) {
                    if (data.Success == true) {
                        
                    }
                    else
                    {
                       
                    }

                },
                error: function () {

                },
                complete: function () {
                }
            });

答案 1 :(得分:1)

这是基于@LeTungAnh和@ ibubi代码的工作代码。我无法帮助,但认为$ post仍然是一个更好的方法。 $ post无效的原因是它没有发送ASP.NET Core所需的application / json内容类型。

function authenticate(username, password) {
    //Get the authenticate api url
    var uriHref = window.location.href;
    var lastIndexOfSlash = uriHref.lastIndexOf('/');
    var apiPath = uriHref.substring(0, lastIndexOfSlash) + "/api";
    var encodedUri = encodeURI(apiPath + "/authenticate/");

    var credentials = {};
    credentials["Username"] = username;
    credentials["Password"] = password;

    var credentialsJson = JSON.stringify(credentials);

    $.ajax({
        url: encodedUri,
        type: 'POST',
        data: credentialsJson,
        contentType: 'application/json',
        success: function (responseJson) {

            var authenticationObject = JSON.parse(responseJson)

            if (authenticationObject.IsSuccess == true) {

                //Ensure the token will expire
                var expiryDate = new Date();
                expiryDate = new Date(expiryDate.setTime(expiryDate.getTime() + 86400000));

                //Set the auth token cookie
                var cookieString = "authToken=" + authenticationObject.Authtoken + "; expires=" + expiryDate.toUTCString() + ";path=/";
                document.cookie = cookieString;

                //Goto the xivic app page
                window.location = "Index.html";
            }
            else {
                //Failed to log in, show error message
                $("#badLoginMessage").css("visibility", "visible");
            }

        },
        error: function () {
            //Failed to log in, show error message
            $("#badLoginMessage").css("visibility", "visible");
        },
        complete: function () {
        }
    });
}