ASP.NET REST POST - JavaScript (jQuery) 在 POST 中发送正文
ASP.NET REST POST - JavaScript (jQuery) Send Body in POST
我有一个 REST 调用,当我从 C# 应用程序调用它时工作正常,但我无法让我的 JavaScript 页面发送 POST 正文中的内容。这是 REST 控制器。请注意,如果我从调用中删除 "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);
}
}
这是 JavaScript 使用 JQuery:
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,你必须post Json对象而不是数组]
$.ajax({
url: encodedUri,
type: 'POST',
data: {
Username: jsonString,Password:password
},
success: function (data) {
if (data.Success == true) {
}
else
{
}
},
error: function () {
},
complete: function () {
}
});
这是基于@LeTungAnh 和@ibubi 代码的工作代码。我忍不住认为 $post 仍然是一个更好的方法。 $post 不工作的原因是它没有发送 application/json 的内容类型,而这正是 ASP.NET Core 所要求的。
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 () {
}
});
}
我有一个 REST 调用,当我从 C# 应用程序调用它时工作正常,但我无法让我的 JavaScript 页面发送 POST 正文中的内容。这是 REST 控制器。请注意,如果我从调用中删除 "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);
}
}
这是 JavaScript 使用 JQuery:
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,你必须post Json对象而不是数组]
$.ajax({
url: encodedUri,
type: 'POST',
data: {
Username: jsonString,Password:password
},
success: function (data) {
if (data.Success == true) {
}
else
{
}
},
error: function () {
},
complete: function () {
}
});
这是基于@LeTungAnh 和@ibubi 代码的工作代码。我忍不住认为 $post 仍然是一个更好的方法。 $post 不工作的原因是它没有发送 application/json 的内容类型,而这正是 ASP.NET Core 所要求的。
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 () {
}
});
}