c# - 我可以在.net MVC 中使用FromBody 和FromUri 吗?

标签 c# .net asp.net-mvc

我有一个 asp.net MVC Controller (不是 web api,不是核心)我正在尝试一个也有 uri 变量的帖子。但我收到了。

FromBody could not be found are you missing a using directive or assembly refrence

对于 FromUri 也是如此

using CFF.CareCenterPortal.BeInCharge.Services;
using CFF.CareCenterPortal.BeInCharge.ViewModels;
using CFF.CareCenterPortal.Web.Controllers.Portal;
using System;
using System.Web.Mvc;

namespace CFF.CareCenterPortal.Web.Controllers.BeInCharge
{
    [Authorize]
    [RoutePrefix("beincharge/caregiver")]
    public class BeInChargeCaregiverController : IdentityController
    {
        [HttpPost] 
        [Route("{id}")]
        public ActionResult EditCaregiver([FromBody()] CareGiverViewModel data, [FromUri()] int id)

        {
            var service = new BeInChargeDataService();
            var result = service.EditCaregiver(data,id,CurrentUser.NameIdentitifier);
            if (result == null)
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.InternalServerError, "An Unhandled Error Occcured");
            }

            if (!String.IsNullOrEmpty(result.Error) && !String.IsNullOrWhiteSpace(result.Error))
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest, result.Error);
            }

            return Json("Success");
        }

最佳答案

can I use FromBody and FromUri in .net MVC?

没有。据我了解,这些属性只是一个 WebAPI 约定。您的选择是使用 WebAPI Controller (非常简单)或编写您自己的 Custom Model Binder for MVC可以检查参数的属性来模拟您的需求。

我不确定您是否知道,但是 MVC ModelBinder 已经从 Route、QueryString 和 Body 获取值以实现参数。

欢迎您查看 Source Code to MVC .最重要的是 ValueProviderFactories ,它有以下方法:

    private static readonly ValueProviderFactoryCollection _factories 
      = new ValueProviderFactoryCollection()
    {
        new ChildActionValueProviderFactory(),
        new FormValueProviderFactory(),
        new JsonValueProviderFactory(),
        new RouteDataValueProviderFactory(),
        new QueryStringValueProviderFactory(),
        new HttpFileCollectionValueProviderFactory(),
        new JQueryFormValueProviderFactory()
    };

这就是 MVC 用来为模型绑定(bind)程序提供值的方法。

例子:

我采用了默认 MVC 网站并进行了以下更改:

/views/home/Index.cshtml

第 8 行:

    <p><a class="btn btn-primary btn-lg js-test">Learn more &raquo;</a></p>

添加到文件底部:

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
        integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
        crossorigin="anonymous"></script>
<script>
    $(document).ready(function () {
        $('.js-test').on('click', function () {
            $.ajax({
                url: '@Url.RouteUrl(new{ action="Name", controller="Home", id=5})',
                data: JSON.stringify({Name: 'My Test Name' }),
                    type: 'POST',
                    dataType: 'json',
                    contentType: "application/json",
            });
        })
    });
</script>

添加了以下文件:

/Models/Home/TestVM.cs

public class TestVM
{
    public string Name {  get; set; }
}

更新 Controller :

/Controllers/HomeController.cs:

    public ActionResult Name(TestVM test, int id)
    {
        System.Diagnostics.Debug.WriteLine(test.Name);
        System.Diagnostics.Debug.WriteLine(id);
        return new  EmptyResult();
    }

现在当点击按钮时,会发出以下请求:

Request URL: http://localhost:53549/Home/Name/5
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:53549
Referrer Policy: no-referrer-when-downgrade
Cache-Control: private
Content-Length: 0
Date: Tue, 03 Jul 2018 17:21:55 GMT
Server: Microsoft-IIS/10.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 23
Content-Type: application/json
Host: localhost:53549
Origin: http://localhost:53549
Pragma: no-cache
Referer: http://localhost:53549/

{Name: "My Test Name"}  
Name
:
"My Test Name"

我的调试窗口打印:

My Test Name

5

My Test Name 是来自 JsonValueProviderFactory 的 ModelBound 和来自 url http://localhost:53549/Home/Name/5 的 id 是来自 RouteDataValueProviderFactory 的 ModelBound。

关于c# - 我可以在.net MVC 中使用FromBody 和FromUri 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51159373/

相关文章:

c# - 提高字符串生成器的性能

c# - 检查字符串是否包含单词

.net - 将静态方法绑定(bind)到 CheckBox 并将参数传递给它

c# - 如何在超时时根据用户类型将用户重定向到 ASP.net MVC 应用程序中的不同 url

asp.net-mvc - MVC : Use Display name as column header with CSVHelper

asp.net-mvc - Windows Azure 上使用 Entity Framework 进行 Asp.net mvc 身份验证

c# - 字符串或二进制数据将被截断 - 添加新行( Entity Framework )

c# - 如何使用 C# 在不知道任何机器名称的情况下找到 LAN 上所有共享的名称?

asp.net - 如何通过ConfigurationManager找到配置文件位置?

.net - Windows 窗体的进度按钮