![](/img/trans.png)
[英]ASP.Net Core 3.1: Controller method always recieves NULL parameter from HttpPost call
[英]How do I use JavaScript to properly call a HttpPost method from .NET Core 3.1 avoiding the 400 error
在 .NET Core 3.1 中進行實驗
我顯然缺少 Core 中 HttpPost 的一個 KEY 元素。 我想將 JSON 傳遞給 controller 並在后面的代碼中從 JSON 獲得我需要的東西。 運行它總是提供 400(錯誤請求)永遠不會進入 function,所以我相信這是一件基本的事情。 我還嘗試使用 jQuery POST 方法$.post("/nodes", item, function () { alert("success");})
並返回 415(不支持的媒體類型)。
我已經嘗試了幾個動作參數 frombody,fromheader,from request。 FromBody 似乎應該是那個。 我根據其他帖子添加了 CORS 只是為了消除。 如果重要的話,純 html 文件在項目中,它不是 cshtml。 除了 jQuery 之外,沒有客戶端框架。我不想要特定於框架的答案(angular、moo、vue、react 等)。 看起來,如果做得正確,我們應該能夠在最基本的層面上做到這一點。 香草 javascript 或 jQuery 的回答會讓我順利上路。
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) ");
});
}
更新對於潛伏者:更改 controller 中的簽名解決了我的問題。 我知道這是一個基本的疏忽。
[HttpPost]
public object Post([FromBody] object value)
{
var foo = "bar";
return value;
}
此外,在編寫時,我在 $.ajax 調用中弄錯了dataType屬性。 這是指返回值與請求中發送的數據負載。
我希望這對你也有幫助。
這里的問題是,當您發布 object 時,您的 controller 需要一個字符串。
您應該首先使用 Postman 進行測試,使用"9f14a706-e750-4b76-8ba5-78d890bbdf0d"
作為有效載荷和 Content-Type:application/json。 如果可行,請嘗試像這樣更改您的 js:
data: JSON.stringify("9f14a706-e750-4b76-8ba5-78d890bbdf0d")
請寫出:
/// 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";
}
}
}
在Startup.cs
中:
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
在startup.cs
的Configure
方法中:
app.UseCors("CorsPolicy");
並添加:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
您正在傳遞包含 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.