Javascript NETMVC5-jQueryAJAX工作,获取API不';T
在我的ASP.NET MVC 5项目中,我已经使用WebApi设置了本地API,并且我正在检查所有更改数据的API中使用ASP.NET标识的用户角色。当我使用jqueryajax向Javascript NETMVC5-jQueryAJAX工作,获取API不';T,javascript,jquery,ajax,asp.net-web-api,fetch-api,Javascript,Jquery,Ajax,Asp.net Web Api,Fetch Api,在我的ASP.NET MVC 5项目中,我已经使用WebApi设置了本地API,并且我正在检查所有更改数据的API中使用ASP.NET标识的用户角色。当我使用jqueryajax向api/createPerson发出POST请求时,效果很好。但是,当我使用自己的获取API库时,服务器返回登录页面的HTML,而不是JSON数据。 正如您所看到的,JSON解析失败(因为它是HTML而不是有效的JSON代码) 但是,如果禁用API控制器中的代码块: if (!User.IsInRole("Admin
api/createPerson
发出POST请求时,效果很好。但是,当我使用自己的获取API库时,服务器返回登录页面的HTML,而不是JSON数据。
正如您所看到的,JSON解析失败(因为它是HTML而不是有效的JSON代码)
但是,如果禁用API控制器中的代码块:
if (!User.IsInRole("Admin"))
return Unauthorized();
服务器正常返回JSON
为什么当我使用jQueryAjax请求时,我的User.IsInRole(“Admin”)
检查返回true
,而当我使用FetchAPI时,它返回false
有效的代码(jQuery AJAX):
$.ajax({
method: "POST",
url: `/api/createPerson/`,
type: "application/json",
data: {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
},
success: function (message) {
// ...
},
error: function (error) {
if (error.responseJSON.modelState)
showValidationMessages(error.responseJSON.modelState);
});
httpFetch.post("/api/createPerson/", {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
}).then(message => {
// ...
})
[HttpPost]
[Route("api/createPerson")]
public IHttpActionResult CreatePerson(PersonDto personDto)
{
//Check for privileges(ADMIN ONLY!)
if (!User.IsInRole("Admin"))
return Unauthorized();
// Check if model state is valid
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Check if person already exists in the database, if true, update it
if (personDto.Id != 0)
{
// Try updating person in db
try
{
var personInDb = _context.Persons.SingleOrDefault(p => p.Id == personDto.Id);
personInDb.FirstName = personDto.FirstName;
personInDb.LastName = personDto.LastName;
personInDb.Gender = personDto.Gender;
personInDb.Email = personDto.Email;
personInDb.BirthDate = personDto.BirthDate;
personInDb.PhoneNumber = personDto.PhoneNumber;
personInDb.StateId = personDto.StateId;
personInDb.CityId = personDto.CityId;
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} updated in the database!");
}
// If person doesn't exist in db, add new person to db
try
{
var person = new Person
{
Id = personDto.Id,
FirstName = personDto.FirstName,
LastName = personDto.LastName,
Gender = personDto.Gender,
Email = personDto.Email,
BirthDate = personDto.BirthDate,
PhoneNumber = personDto.PhoneNumber,
StateId = personDto.StateId,
CityId = personDto.CityId
};
_context.Persons.Add(person);
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} added to the database!");
}
不起作用的代码(获取API):
$.ajax({
method: "POST",
url: `/api/createPerson/`,
type: "application/json",
data: {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
},
success: function (message) {
// ...
},
error: function (error) {
if (error.responseJSON.modelState)
showValidationMessages(error.responseJSON.modelState);
});
httpFetch.post("/api/createPerson/", {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
}).then(message => {
// ...
})
[HttpPost]
[Route("api/createPerson")]
public IHttpActionResult CreatePerson(PersonDto personDto)
{
//Check for privileges(ADMIN ONLY!)
if (!User.IsInRole("Admin"))
return Unauthorized();
// Check if model state is valid
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Check if person already exists in the database, if true, update it
if (personDto.Id != 0)
{
// Try updating person in db
try
{
var personInDb = _context.Persons.SingleOrDefault(p => p.Id == personDto.Id);
personInDb.FirstName = personDto.FirstName;
personInDb.LastName = personDto.LastName;
personInDb.Gender = personDto.Gender;
personInDb.Email = personDto.Email;
personInDb.BirthDate = personDto.BirthDate;
personInDb.PhoneNumber = personDto.PhoneNumber;
personInDb.StateId = personDto.StateId;
personInDb.CityId = personDto.CityId;
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} updated in the database!");
}
// If person doesn't exist in db, add new person to db
try
{
var person = new Person
{
Id = personDto.Id,
FirstName = personDto.FirstName,
LastName = personDto.LastName,
Gender = personDto.Gender,
Email = personDto.Email,
BirthDate = personDto.BirthDate,
PhoneNumber = personDto.PhoneNumber,
StateId = personDto.StateId,
CityId = personDto.CityId
};
_context.Persons.Add(person);
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} added to the database!");
}
API控制器代码:
$.ajax({
method: "POST",
url: `/api/createPerson/`,
type: "application/json",
data: {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
},
success: function (message) {
// ...
},
error: function (error) {
if (error.responseJSON.modelState)
showValidationMessages(error.responseJSON.modelState);
});
httpFetch.post("/api/createPerson/", {
id: idHidden,
firstName: firstNameTxt.val(),
lastName: lastNameTxt.val(),
phoneNumber: phoneTxt.val(),
gender: genderDropDown.val(),
birthDate: birthdateTxt.val(),
email: emailTxt.val(),
stateId: statesDropDown.val(),
cityId: citiesDropDown.val()
}).then(message => {
// ...
})
[HttpPost]
[Route("api/createPerson")]
public IHttpActionResult CreatePerson(PersonDto personDto)
{
//Check for privileges(ADMIN ONLY!)
if (!User.IsInRole("Admin"))
return Unauthorized();
// Check if model state is valid
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Check if person already exists in the database, if true, update it
if (personDto.Id != 0)
{
// Try updating person in db
try
{
var personInDb = _context.Persons.SingleOrDefault(p => p.Id == personDto.Id);
personInDb.FirstName = personDto.FirstName;
personInDb.LastName = personDto.LastName;
personInDb.Gender = personDto.Gender;
personInDb.Email = personDto.Email;
personInDb.BirthDate = personDto.BirthDate;
personInDb.PhoneNumber = personDto.PhoneNumber;
personInDb.StateId = personDto.StateId;
personInDb.CityId = personDto.CityId;
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} updated in the database!");
}
// If person doesn't exist in db, add new person to db
try
{
var person = new Person
{
Id = personDto.Id,
FirstName = personDto.FirstName,
LastName = personDto.LastName,
Gender = personDto.Gender,
Email = personDto.Email,
BirthDate = personDto.BirthDate,
PhoneNumber = personDto.PhoneNumber,
StateId = personDto.StateId,
CityId = personDto.CityId
};
_context.Persons.Add(person);
_context.SaveChanges();
}
catch (Exception)
{
// if ERROR
return BadRequest(ModelState);
}
// if SUCCESS
return Ok($"{personDto.FirstName} {personDto.LastName} added to the database!");
}
我的获取API库代码段:
"use strict";
function httpHelper() {
this.post = async function (url, data) {
let response = await fetch(url, {
method: "POST",
headers: { "Content-type": "application/json" },
body: JSON.stringify(data)
});
let resData = await response.json();
return resData;
}
}
这个问题与以下答案有关: 问题是fetch默认情况下不发送身份验证数据。您必须在获取请求中显式声明凭据:“include” 由于默认情况下不发送授权数据,因此当用户操作未经授权时,服务器将返回显示给用户的html。此html无法反序列化为json