[英]HttpContext.Request.Form threw an exception of type 'System.InvalidOperationException' - why?
I have a strange problem.我有一个奇怪的问题。 We are using C# for an ASP.NET MVC application, and JavaScript with jQuery and Data Tables for the frontend.
我们将 C# 用于 ASP.NET MVC 应用程序,将 JavaScript 与 jQuery 和数据表用于前端。 In the frontend, a part of the code looks like this:
在前端,部分代码如下所示:
table: "#restapiusers",
ajax: {
create: { url: "/restapiuser/RegisterUser" },
edit: { url: "/restapiuser/EditUser" }
},
The thing is that although both endpoints RegisterUser and EditUser get passed the payload in the same manner, only EditUser works.问题是,尽管 RegisterUser 和 EditUser 这两个端点都以相同的方式传递有效负载,但只有 EditUser 有效。
[HttpPost]
public async Task<JsonResult> RegisterUser(RestApi_UserModel user_short)
{
var param = HttpContext.Request.Form.Keys.FirstOrDefault();
When I set a breakpoint to the above line and move the mouse cursor over "Form", it says that HttpContext.Request.Form threw an exception of type 'System.InvalidOperationException'.当我在上面的行设置断点并将鼠标 cursor 移到“表单”上时,它说 HttpContext.Request.Form 抛出了类型为“System.InvalidOperationException”的异常。
The beginning of EditUser looks exactly the same and there the error does not occur. EditUser 的开头看起来完全一样,并且不会发生错误。 I am puzzled how this is possible.
我很困惑这怎么可能。
In one of the code files there was the following text:在其中一个代码文件中有以下文本:
// Defaults for DT-Editor for all future instances
$.extend(true, $.fn.dataTable.Editor.defaults, {
ajax: {
create: {
type: 'POST',
//*** contentType: "application/json",
//*** dataType: 'json',
data: function (d) {
d = JSON.stringify(Object.values(d.data))
console.info("Payload", d);
return d
},
},
edit: {
type: 'POST',
//contentType: "application/json",
//dataType: 'json',
data: function (d) {
d = JSON.stringify(Object.values(d.data))
console.info("Payload", d);
return d
},
}
},
idSrc: 'id',
});
I commented out the lines I marked with "***" and now it works.我注释掉了我用“***”标记的行,现在它可以工作了。 Apparently the contentType must not be "application/json" for the data to be passed via the first or default key of the form.
显然,对于要通过表单的第一个或默认键传递的数据,contentType 不能是“application/json”。
Change Request.Form to Request.Query将 Request.Form 更改为 Request.Query
public async Task<JsonResult> RegisterUser(RestApi_UserModel user_short)
{
var param = HttpContext.Request.Query.Keys.FirstOrDefault();
}```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.