Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASP.NET5 MVC6的模型绑定问题_C#_Asp.net_Angularjs_Json_Asp.net Core Mvc - Fatal编程技术网

C# ASP.NET5 MVC6的模型绑定问题

C# ASP.NET5 MVC6的模型绑定问题,c#,asp.net,angularjs,json,asp.net-core-mvc,C#,Asp.net,Angularjs,Json,Asp.net Core Mvc,我试图将一些JSON数据以角度形式发布到我的ASP.NET5 MVC6控制器操作中。模型活页夹似乎不起作用。不知道我错过了什么 我的ASP控制器: public class DefaultController : Controller { public IActionResult Index() { return View(); } [HttpPost] public IActionResult SubmitTest(QTestViewM

我试图将一些JSON数据以角度形式发布到我的ASP.NET5 MVC6控制器操作中。模型活页夹似乎不起作用。不知道我错过了什么

我的ASP控制器:

public class DefaultController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult SubmitTest(QTestViewModel model)
    {
        return Json("true");
    }
}
angular.module("testActiveMq", [])
.controller("MqTestController", ["$scope", "$http", function ($scope, $http) {
    // Submit Form
    $scope.submitForm = function () {
        debugger;
        var formData = (this.data) ? angular.toJson(this.data) : null;
        if (formData && this.qForm && this.qForm.$valid) {
            $http({
                url: "/Default/SubmitTest",
                data: formData,
                method: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            })
            .then(function successCallback(response) {
                debugger;
                // this callback will be called asynchronously
                // when the response is available
            }, function errorCallback(response) {
                debugger;
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
        }
    };
}])
我的角度控制器:

public class DefaultController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public IActionResult SubmitTest(QTestViewModel model)
    {
        return Json("true");
    }
}
angular.module("testActiveMq", [])
.controller("MqTestController", ["$scope", "$http", function ($scope, $http) {
    // Submit Form
    $scope.submitForm = function () {
        debugger;
        var formData = (this.data) ? angular.toJson(this.data) : null;
        if (formData && this.qForm && this.qForm.$valid) {
            $http({
                url: "/Default/SubmitTest",
                data: formData,
                method: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            })
            .then(function successCallback(response) {
                debugger;
                // this callback will be called asynchronously
                // when the response is available
            }, function errorCallback(response) {
                debugger;
                // called asynchronously if an error occurs
                // or server returns response with an error status.
            });
        }
    };
}])
我的视图模型:

public class QTestViewModel
{
    public string MqBrokerUri { get; set; }

    public string ClientId { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public int TotalRequests { get; set; }

    public int MaxConcurrentRequests { get; set; }

    public int DelayBetweenThreads { get; set; }
}
当我发出请求时,HTTP头是

POST /Default/SubmitTest HTTP/1.1
Host: localhost:50877
Connection: keep-alive
Content-Length: 225
Accept: application/json, text/plain, */*
Origin: http://localhost:50877
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:50877/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
我的表单数据看起来是这样的

{"MqBrokerUri":"ssl://broker-uri:1616?transport.acceptInvalidBrokerCert=true","ClientId":"MqLoadTest","UserName":"myunm","Password":"mypwd","TotalRequests":100,"MaxConcurrentRequests":10,"DelayBetweenThreads":1}

我觉得我错过了一些非常明显的东西。为什么我的JSON数据没有绑定到我的模型?当然,我不需要一个定制的模型绑定器来完成这么简单的事情吗?

在MVC 5和早期版本中,您的代码足以在控制器中接收模型。 但是,在MVC 6中,您还需要在控制器操作中设置
[FromBody]
参数:

[HttpPost]
public IActionResult SubmitTest([FromBody]QTestViewModel model)
{
    return Json("true");
}
不确定为什么这是MVC6中的一个要求,但是如果您不添加FromBody属性,您的模型将保留其默认值

var allowedBindingSource = bindingContext.BindingSource;
if (allowedBindingSource == null ||
    !allowedBindingSource.CanAcceptDataFrom(BindingSource.Body))
{
    // Formatters are opt-in. This model either didn't specify [FromBody] or specified something
    // incompatible so let other binders run.
    return ModelBindingResult.NoResultAsync;
}
  • 例如,检查官方文件中的示例

  • 在深入研究源代码之后,似乎只会接受专门启用body绑定源代码的模型,该绑定源代码是通过添加属性完成的

    var allowedBindingSource = bindingContext.BindingSource;
    if (allowedBindingSource == null ||
        !allowedBindingSource.CanAcceptDataFrom(BindingSource.Body))
    {
        // Formatters are opt-in. This model either didn't specify [FromBody] or specified something
        // incompatible so let other binders run.
        return ModelBindingResult.NoResultAsync;
    }
    

PS.Angular默认情况下是字符串化json对象,但是如果您使用类似jQuery的东西,您还需要手动调用
json.stringify

有时使用json会更好

var jsonResult=json("true");
jsonResult.maxJsonLength=int32.maxValue
return jsonresult;

希望对您有所帮助。

[edit]看来这个答案不正确。我的问题是由于操作参数的名称与对象的一个属性相同。这导致MVC使用前缀来防止歧义。我不同意这是含糊不清的,我正在讨论这个问题


我刚刚在Github上记录了一个错误。如果您的参数没有命名为参数类型的CamelCase,那么它希望负载中的字段以参数名称作为前缀

您可以通过在操作参数之前添加[Bind(Prefix=”“)]来修复此问题。

公共IActionResult SubmitTest([Bind(Prefix=”“)]QTestViewModel模型)

好的@Daniel J.G.Ansare不适合我 我不得不使用 [FromForm]而不是[FromBody]来让Bing工作

  [HttpPost]
public IActionResult SubmitTest([FromForm]QTestViewModel model)
{
    return Json("true");
}

尝试将
public-IActionResult-SubmitTest(qtestview-model)
更改为
public-IActionResult-SubmitTest(string-model)
作为一个快速测试,并查看返回的结果。还可以尝试
public-IActionResult-SubmitTest([FromBody]qtestview-model)
您缺少
JsonRequestBehavior.AllowGet
。更改为
返回Json(“true”,JsonRequestBehavior.AllowGet)这不起作用。viewmodel中的所有值到达控制器时都为空。