C# 为什么我的ajax/fetch调用在控制器中没有路由的情况下不能工作?
我在这个问题上已经花了很长时间,我不明白为什么我的jquery ajax帖子不能与C# 为什么我的ajax/fetch调用在控制器中没有路由的情况下不能工作?,c#,ajax,asp.net-core-mvc,C#,Ajax,Asp.net Core Mvc,我在这个问题上已经花了很长时间,我不明白为什么我的jquery ajax帖子不能与SurveyController.cs: [HttpPost] public ActionResult AddComment(Survey survey) { if (survey == null) { return NotFound(); } if (su
SurveyController.cs
:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
阿贾克斯:
从Startup.cs路由:
[HttpPost]
public ActionResult AddComment(Survey survey)
{
if (survey == null)
{
return NotFound();
}
if (survey != null)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
}
return null;
}
app.UseMvc(routes => {
routes.MapRoute(name: "Error", template: "Error",
defaults: new { controller = "Error", action = "Error" });
routes.MapRoute(
name: "default", template: "{controller}/{action}/{id?}",
defaults: new { controller = "MyProjects", action = "Index" });
});
它在控制台中没有给我任何错误,但在控制器中没有遇到任何断点
仅当我在控制器中使用[Route(“comments/new”)]
和在Ajax中使用url:“/comments/new/AddComment”
时,它才起作用
我想控制器需要使用[HttpPost]
才能使用[ValidateAntiForgeryToken]
。但无论如何,我的Ajax和控制器都是根据我在这里找到的大多数Ajax文章的流行示例编写的,我不知道为什么它不起作用
编辑:
我尝试使用Fetch调用实现相同的功能:
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
fetch(`/comments/new?`,
{
method: 'POST',
body: JSON.stringify({ queryParams }), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
同样的结果。
我注意到,在控制台日志中的XHR
中,调用类型是GET
notPOST
,与AJAX
调用相同。为什么?
更新:
因为某种原因,当改变
fetch(/comments/new?
到
fetch(/Survey/AddComment
XHR给我的仍然是相同的调用URL:
http://localhost:58256/comments/new?Name=aaa&Change=aaa&Opinion=good
不管我在那里看到什么,它都不会改变!!!(?)
更新:
删除[Route(“comments/new”)]
并离开fetch(“/Survey/AddComment”
后,根本没有调用
更新
清除整个浏览器的数据后,使用:
控制器:
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey)
{
if (survey == null)
{
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
获取:
const data = {
Name: this.state.surveyState.name,
Change: this.state.surveyState.change,
Opinion: this.state.surveyState.opinion
};
fetch("/Survey/AddComment",
{
method: 'POST',
body: JSON.stringify({ data}), // data can be `string` or {object}!
headers: { 'Content-Type': 'application/json' },
credentials: 'include'
}
)
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(error => {
console.error(error);
});
我仍在获取呼叫URL的XHR日志:
http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
为什么?线路
name: "default", template: "{controller}/{action}/{id?}",
表示路径/Survey/AddComment
将调用该操作
SurveyController.AddComment()
标有“”的id是可选的({id?})
如果要在控制器中定义路由,可以执行以下操作
[Route("[controller]/[action]")]
public class SurveyController : Controller {
[HttpPost]
public ActionResult AddComment(Survey survey)
{
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Content("Added");
}
}
在这两种情况下,如果发送POST请求,则必须使用[HttpPost]标记操作。客户端表示它正在发送application/json
,但是
const queryParams = `Name=${this.state.surveyState.name}&Change=${this.state.surveyState.change}&Opinion=${this.state.surveyState.opinion}`;
不是JSON。看起来更像是在查询字符串中发送的数据
构造有效的JSON负载
const data = {
Name: ${this.state.surveyState.name},
Change: ${this.state.surveyState.change},
Opinion: ${this.state.surveyState.opinion}
};
并将其以正确的格式发送到服务器
$.ajax({
type: 'POST',
url: "/Survey/AddComment",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json"
});
最后,使用[FromBody]
[HttpPost]
public IActionResult AddComment([FromBody]Survey survey) {
if (survey == null) {
return BadRequest();
}
survey.Time = DateTime.Now;
_context.Surveys.Add(survey);
_context.SaveChanges();
return Ok();
}
如果您添加类属性、控制器的类名(SurveyController???)以及action AddComment()的属性,这会有所帮助可能还有Startup.cs的路由定义。当然,如果你想处理一篇文章,你必须使用HttpPost属性。@koalabruder updated我用fetch调用再次尝试,结果相同(请参见编辑的问题)。我注意到,在XHR
控制台日志中,调用类型是GET
,而不是POST
,也用于ajax
调用。我不明白为什么?我喜欢你的提议,但它没有通过该操作,因为某些原因我喜欢你发布的内容,而且没有任何内容符合public IActionResult addcommon中的断点t([FromBody]Survey Survey)
我用fetch调用再次尝试,结果相同(请参见编辑的问题)。我注意到,在XHR
控制台日志中,调用类型是GET
,而不是POST
,也用于ajax
调用。我不明白为什么?@Przemyslaw.Pszemek在您的更新中,您似乎仍然发送了错误的数据。请仔细查看我的回答,并注意我是如何构建要发送的数据的。@我尝试了您的方法,p请看关于这个问题的最新更新。由于某种原因,我进入了XHR
日志旧URL:http://localhost:58256/comments/new?Name=aa&Change=aaa&Opinion=good
,即使将获取URL更改为:/Survey/AddComment
。使用格式:${this.state.surveyState.name}也会得到相同的结果
对于properties.P.S.您认为,React应用程序调用Fetch有关系吗?