[英]How do I use JavaScript to properly call a HttpPost method from .NET Core 3.1 avoiding the 400 error
Experimenting in .NET Core 3.1在 .NET Core 3.1 中进行实验
I am clearly missing a KEY element of the HttpPost in Core.我显然缺少 Core 中 HttpPost 的一个 KEY 元素。 I would like to pass JSON to the controller and get what I need from the JSON in code behind.我想将 JSON 传递给 controller 并在后面的代码中从 JSON 获得我需要的东西。 Running this always supplies 400 (Bad Request) never making it into the function so i am lead to believe it is a basic thing.运行它总是提供 400(错误请求)永远不会进入 function,所以我相信这是一件基本的事情。 I have also tried using the jQuery POST method $.post("/nodes", item, function () { alert("success");})
and that returns a 415 (Unsupported Media Type).我还尝试使用 jQuery POST 方法$.post("/nodes", item, function () { alert("success");})
并返回 415(不支持的媒体类型)。
I have tried several action parameters frombody, fromheader, from request.我已经尝试了几个动作参数 frombody,fromheader,from request。 FromBody seems like it should be the one. FromBody 似乎应该是那个。 I have added the CORS based on other posts just to eliminate.我根据其他帖子添加了 CORS 只是为了消除。 The pure html file IS in the project if it matters it is not a cshtml.如果重要的话,纯 html 文件在项目中,它不是 cshtml。 There are no client-side frameworks other than jQuery. I do not want framework specific answers (angular, moo, vue, react, etc.).除了 jQuery 之外,没有客户端框架。我不想要特定于框架的答案(angular、moo、vue、react 等)。 It seems that if done correctly we should be able to do it at the most basic level.看起来,如果做得正确,我们应该能够在最基本的层面上做到这一点。 An answer in vanilla javascript or jQuery would get me on my way nicely.香草 javascript 或 jQuery 的回答会让我顺利上路。
fwiw: The GETs all work. fwiw:GET 都有效。
// Client side JavaScript.
var item = {
id: "9f14a706-e750-4b76-8ba5-78d890bbdf0d"
};
$.ajax({
type: "POST",
accepts: "application/json",
url: '/nodes',
contentType: "application/json",
data: JSON.stringify(item),
error: function (jqXHR, textStatus, errorThrown) {
console.error("Something went wrong!");
console.error(textStatus);
console.error(errorThrown);
},
success: function (result) {
console.log('Testing');
}
});
/// NodesController.cs
namespace INM.Controllers
{
[Route("[controller]")]
[ApiController]
public class NodesController : ControllerBase
{
[HttpPost]
public void Post([FromBody] string value)
{
var foo = "bar";
}
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
var foo = "bar";
}
}
}
///StartUp.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddCors();
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
DeveloperExceptionPageOptions developerExceptionPageOptions = new DeveloperExceptionPageOptions
{
SourceCodeLineCount = 10
};
app.UseCors(builder =>
{
builder.WithOrigins("http://localhost:61246/")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowAnyOrigin();
//.AllowCredentials()
});
app.UseDeveloperExceptionPage(developerExceptionPageOptions);
}
FileServerOptions fileServerOptions = new FileServerOptions();
fileServerOptions.DefaultFilesOptions.DefaultFileNames.Clear();
fileServerOptions.DefaultFilesOptions.DefaultFileNames.Add("INM.html");
app.UseFileServer(fileServerOptions); // combines app.UseDefaultFiles(); & app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run(async (context) =>
{
//throw new Exception("Some proc err");
await context.Response.WriteAsync("Hello World from Startup.cs (Configure) ");
});
}
UPDATE For the lurkers: Changing the signature in the controller fixed my issues.更新对于潜伏者:更改 controller 中的签名解决了我的问题。 I knew it was a basic oversight.我知道这是一个基本的疏忽。
[HttpPost]
public object Post([FromBody] object value)
{
var foo = "bar";
return value;
}
Also, while writing I was mistaken about the dataType property in a $.ajax call.此外,在编写时,我在 $.ajax 调用中弄错了dataType属性。 This refers to the return value vs the data payload sent in the request.这是指返回值与请求中发送的数据负载。
I hope this helps you too.我希望这对你也有帮助。
Problem here, is that your controller is expecting a string, while you are posting an object.这里的问题是,当您发布 object 时,您的 controller 需要一个字符串。
You should test with Postman first, use "9f14a706-e750-4b76-8ba5-78d890bbdf0d"
as payload and Content-Type: application/json.您应该首先使用 Postman 进行测试,使用"9f14a706-e750-4b76-8ba5-78d890bbdf0d"
作为有效载荷和 Content-Type:application/json。 If that works, try changing your js like this:如果可行,请尝试像这样更改您的 js:
data: JSON.stringify("9f14a706-e750-4b76-8ba5-78d890bbdf0d")
Please write:请写出:
/// NodesController.cs
namespace INM.Controllers
{
[Route("[controller]")]
[ApiController]
public class NodesController : ControllerBase
{
[HttpPost]
[Route("api/[Controller]/[action]")]
public void Post([FromBody] string value)
{
var foo = "bar";
}
[HttpPut("{id}")]
[Route("api/[Controller]/[action]/:id")]
public void Put(int id, [FromBody] string value)
{
var foo = "bar";
}
}
}
and in Startup.cs
:在Startup.cs
中:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
and in the Configure
method in startup.cs
:在startup.cs
的Configure
方法中:
app.UseCors("CorsPolicy");
and add:并添加:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
you are passing the object containing id attribute while on server-side you are receiving only string as a parameter from body so change your code to have one string value in the body like this see if it works for you您正在传递包含 id 属性的 object,而在服务器端您仅从 body 接收字符串作为参数,因此更改您的代码以在 body 中具有一个字符串值,如下所示,看看它是否适合您
var item = "9f14a706-e750-4b76-8ba5-78d890bbdf0d";
$.ajax({
type: "POST",
accepts: "application/json",
url: '/nodes',
contentType: "application/json",
data: JSON.stringify(item),
error: function (jqXHR, textStatus, errorThrown) {
console.error("Something went wrong!");
console.error(textStatus);
console.error(errorThrown);
},
success: function (result) {
console.log('Testing');
}
}); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.