简体   繁体   English

NET MVC中可以使用FromBody和FromUri吗?

[英]can I use FromBody and FromUri in .net MVC?

I have an asp.net MVC controller (not web api, not core) I am attempting a post that also has a uri variable. 我有一个asp.net MVC控制器(不是Web api,不是核心),我正在尝试一个也具有uri变量的帖子。 but I am receiving. 但我收到了

FromBody could not be found are you missing a using directive or assembly refrence 如果缺少using指令或程序集引用,则找不到FromBody

same for FromUri 对于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? NET MVC中可以使用FromBody和FromUri吗?

No. From what I understand, those attributes are only a WebAPI convention. 不。据我了解,这些属性只是WebAPI约定。 Your options are to either use WebAPI Controller (very simple) or write your own Custom Model Binder for MVC that can inspect the parameter for attributes to mimic your needs. 您可以选择使用WebAPI Controller(非常简单),也可以编写自己的MVC定制模型绑定程序,该模板可以检查参数的属性以模仿您的需求。

I'm not sure you're aware, but the MVC ModelBinder already gets values from Route, QueryString and Body to materialize parameters. 我不确定您是否知道,但是MVC ModelBinder已经从Route,QueryString和Body获取值以实现参数。

You're welcome to look at the Source Code to MVC . 欢迎您查看MVC源代码 The most important is the ValueProviderFactories , which has the following method: 最重要的是ValueProviderFactories ,它具有以下方法:

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

This is what MVC uses to provider values to the model binder. 这就是MVC用于向模型绑定程序提供值的方法。

Example: 例:

I've taken the Default MVC website and made the following changes: 我已经使用了默认MVC网站,并进行了以下更改:

/views/home/Index.cshtml /views/home/Index.cshtml

line: 8: 行:8:

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

Added to the bottom of the file: 添加到文件底部:

<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>

Added the following File: 添加了以下文件:

/Models/Home/TestVM.cs /Models/Home/TestVM.cs

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

Updated the controller: 更新了控制器:

/Controllers/HomeController.cs: /Controllers/HomeController.cs:

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

Now when the button is clicked, the following request is made: 现在,单击按钮时,将发出以下请求:

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 Debug window Prints: 我的调试窗口打印:

My Test Name 我的测试名称

5 5

The My Test Name is ModelBound from the JsonValueProviderFactory and the id which comes from the url http://localhost:53549/Home/Name/5 is ModelBound from the RouteDataValueProviderFactory . My Test NameJsonValueProviderFactory ModelBound,来自URL http://localhost:53549/Home/Name/5的id是RouteDataValueProviderFactory ModelBound。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在MVC 5中使用FromUri或FromBody - Using FromUri OR FromBody in MVC 5 同时阅读FromUri和FromBody - Reading FromUri and FromBody at the same time 是否可以在FromURI和FromBody上创建参数绑定? - Is it possible to create a parameter binding on both FromURI and FromBody? 通过FromUri或FromBody将Web API与JSON中的参数一起使用 - Using web API with parameters in JSON with FromUri or FromBody 带有两个参数fromuri和frombody的Swagger-WebAPi - Swagger-WebAPi with two params fromuri and frombody 是否可以在 ASP.NET MVC [FromBody] 控制器方法参数中使用多态? - Is it possible to use polymorphism in and ASP.NET MVC [FromBody] controller method parameter? Asp.net MVC使用[FromUri]将url参数解析为对象 - Asp.net MVC parse url parameter to object using [FromUri] 什么是 ASP.NET MVC 中的 WebApi [FromUri] 等价物? - What's the WebApi [FromUri] equivalent in ASP.NET MVC? 在Asp.Net WebApi操作中使用FromUri属性时,如果没有路由或查询字符串参数,是否可以强制实例化复杂的类? - Can I force a complex class to be instantiated when using FromUri attribute in Asp.Net WebApi action without route or query string parameters? 同时使用[FromUri]和[FromBody]绑定复杂的Web Api方法参数 - Using [FromUri] and [FromBody] simultaneously to bind a complex Web Api method parameter
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM