ASP.NET5 MVC6的模型绑定问题

Ro *_*Hit 12 c# asp.net json angularjs asp.net-core-mvc

我试图在角色表单上发布一些JSON数据到我的ASP.NET5 MVC6控制器动作.模型绑定器似乎不起作用.不知道我在这里缺少什么.

我的ASP控制器:

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

    [HttpPost]
    public IActionResult SubmitTest(QTestViewModel model)
    {
        return Json("true");
    }
}
Run Code Online (Sandbox Code Playgroud)

我的角度控制器:

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.
            });
        }
    };
}])
Run Code Online (Sandbox Code Playgroud)

我的视图模型:

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; }
}
Run Code Online (Sandbox Code Playgroud)

当我发出请求时,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
Run Code Online (Sandbox Code Playgroud)

我的表单数据看起来像..

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

我觉得我错过了一些非常明显的东西.为什么我的JSON数据不能绑定到我的模型?当然,我不需要定制模型粘合剂来实现这么简单的事情吗?

Dan*_*.G. 12

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

[HttpPost]
public IActionResult SubmitTest([FromBody]QTestViewModel model)
{
    return Json("true");
}
Run Code Online (Sandbox Code Playgroud)

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

  • 检查官方文档中的Web API教程.

  • 在深入挖掘源代码之后,似乎BodyModelBinder只会接受专门启用了body绑定源的模型,这样就完成了添加[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;
    }
    
    Run Code Online (Sandbox Code Playgroud)

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