gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:05:17 24 4
gpt4 key购买 nike

我有一个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com