ASP.NET5 MVC6 的模型绑定问题

Model Binding Issue with ASP.NET5 MVC6

我正在尝试 post JSON 表单上的一些 JSON 数据到我的 ASP.NET5 MVC6 控制器操作。模型活页夹似乎不起作用。不确定我在这里遗漏了什么。

我的ASP控制器:

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

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

我的Angular控制器:

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 Headers 是..

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");
}

不确定为什么这是 MVC 6 中的要求,但如果您不添加 FromBody 属性,您的模型将保留其默认值。

  • 例如查看官方文档中的Web API tutorial

  • 在深入研究源代码后,似乎是 BodyModelBinder will only accept models that specifically enabled the body binding source, which is done adding the [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;
    }
    

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

有时 json 最好使用它

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

希望对您有所帮助。

[edit] 看来这个答案不正确。我的问题是由于 Action 参数被命名为与对象的属性之一相同。这导致 MVC 使用前缀来防止歧义。我不同意它是模棱两可的,我正在 Github.

上讨论这个问题

我刚刚在 Github 上记录了关于此的错误。似乎如果您的参数未命名为参数类型的 CamelCase,那么它希望有效负载中的字段以参数名称为前缀。

您可以通过在 Action 的参数前添加 [Bind(Prefix="")] 来解决此问题。 public IActionResult SubmitTest([Bind(Prefix="")]QTestViewModel model)

好的@Daniel J.G。回答对我不起作用 我不得不使用 [FromForm] 而不是 [FromBody] 使 binging 正常工作

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