gpt4 book ai didi

javascript - ASP.NET REST POST - JavaScript (jQuery) 在 POST 中发送正文

转载 作者:行者123 更新时间:2023-12-01 02:50:05 25 4
gpt4 key购买 nike

我有一个 REST 调用,当我从 C# 应用程序调用它时工作正常,但我无法让我的 JavaScript 页面发送 POST 正文中的内容。这是 REST Controller 。请注意,如果我从调用中删除“FromBody”属性,下面的 JavaScript 可以正常工作。

[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");
}
});
}

最佳答案

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

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

}
else
{

}

},
error: function () {

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

关于javascript - ASP.NET REST POST - JavaScript (jQuery) 在 POST 中发送正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47027677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com