c# - ASP.NET5 MVC6 的模型绑定(bind)问题

标签 c# asp.net angularjs json asp.net-core-mvc

我试图将一些 JSON 数据以 Angular 形式发布到我的 ASP.NET5 MVC6 Controller 操作。模型 Binder 似乎不起作用。不确定我在这里遗漏了什么。

我的 ASP Controller :

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

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

我的 Angular Controller :

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.
            });
        }
    };
}])

我的 View 模型:

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

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 数据没有绑定(bind)到我的模型?这么简单的事情我肯定不需要自定义模型 Binder 吗?

最佳答案

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

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

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

  • 例如检查 Web API tutorial在官方文档中。

  • 在深入研究源代码后,似乎是 BodyModelBinder将只接受专门启用 body 绑定(bind)源的模型,添加 [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;
    }
    

附言。 Angular 默认对 json 对象进行字符串化,但如果您使用 jQuery 之类的东西,您还需要手动调用 JSON.stringify

关于c# - ASP.NET5 MVC6 的模型绑定(bind)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080796/

相关文章:

c# - 如何使用 SSIS 脚本任务 C# 2005 或 2008 解压缩包含多个文件的文件夹?

c# - 通过 WCF 发送大型 Xml 字符串的最有效解决方案?

c# - 使用正则表达式替换字符但不替换转义字符

c# - c# 中 asp.net 代码隐藏的变量作用域(希望是简单的!)

asp.net - 结合 jQuery 模式对话框和 ASP.net 服务器端事件的正确方法是什么?

c# - GroupJoin 和包含

asp.net - 如何在 Windows 10 上使用 IIS8 注册 .Net 4.5.1

javascript - 指令到指令通信: controller empty ( ={ } )- AngularJS

javascript - 未捕获( promise )DOMException : The element has no supported sources

javascript - 为什么需要注入(inject)服务、常量等?