WebAPI Selfhost:无法将多个参数绑定到请求的内容

问题描述 投票:0回答:5

下面的代码经过简化以显示必要性。我可以知道出了什么问题吗?我似乎无法使用 [FromBody] 属性检索两个参数(在本例中为 A 和 B)。

错误消息是“无法将多个参数('A'和'B')绑定到请求的内容”

如果我只有 A 或 B 就完全没问题了。

网络API:

[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromBody] int A, [FromBody] int B)

客户:

HttpClient client = new HttpClient();
var content = new FormUrlEncodedContent(
    new Dictionary<string, string> {
        { "A", "123" },
        { "B", "456" }
    });
client.PostAsync("http://localhost/API/Test", content).Result;
c# asp.net-web-api
5个回答
68
投票

我认为 Web Api 不支持多个 [FromBody] 参数。但是您可以使用 Api 模型,将更多参数传递给您的 api 操作。:

public class YourApiModel
{
    public int A{ get; set; }

    public int B { get; set; }

    //...other properties    
}

之后,您可以简单地在 API 控制器测试中使用它:

    // POST: api/test
    public IHttpActionResult Post([FromBody] YourApiModel model)
    {
        //do something
    }

希望有帮助。


12
投票

尝试 Web API 代码:

[DataContract]
public class Model
{
    [DataMember]
    public int A { get; set; }

    [DataMember]
    public int B { get; set; }
}

[Route("API/Test"), HttpPost]
public IHttpActionResult Test([FromUri] Model model)

0
投票

在开发用于 Active Directory 身份验证的 C# REST Web API 时遇到类似的错误,请参阅下面的错误消息。

{ "Message": "发生错误。", "ExceptionMessage": "无法将多个参数('userName' 和 'passWord')绑定到请求的内容。", "ExceptionType": "System.InvalidOperationException", “StackTrace”:“在System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext,CancellationToken取消令牌) 在 System.Web.Http.Controllers.ActionFilterResult.d__5.MoveNext() --- 从先前抛出异常的位置开始的堆栈跟踪结束 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()" }

我能够使用下面的代码解决它

// code with issue 
[HttpPost]
        // POST:  api/Showcredential
        public string Post([FromBody]string userName, [FromBody]string passWord)
        {
            return "Username: " + userName +" " + "Password: " + passWord;
        }




// code used to resolve the issue

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Newtonsoft.Json;

namespace ActiveDirectoryRESTApi.Controllers
{

    
    public class ShowCredentialController : ApiController
    {


        public class Loginparam
        {
            public object username { get; set; }
            public object password { get; set; }
        }



        [HttpPost]


        public object Post([FromBody()] object Loginvalues)
        {

            var sessionresponse = new Loginparam();
            string rawrequest = Loginvalues.ToString();
            var jsonResulttodict = JsonConvert.DeserializeObject<Dictionary<string, object>>(rawrequest);
            string rsusername = jsonResulttodict["username"].ToString();
            string rspassword = jsonResulttodict["password"].ToString();


            return "Username: " + rsusername + " " + "Password: " + rspassword;

            
        }

    }
}

0
投票

我编写了一个通用类来管理所有数据类型作为列表,发送所有内容。 然后在你的身上我可以,例如:

int=1,int=3,int=5,string=fdsg,bool=0,ecc...

[HttpPost]
public object Post([FromBody] Generic values)
{
    return values.String;
}

public class Generic
{
    public List<Nullable<byte>> Byte { get; set; }
    public List<Nullable<sbyte>> Sbyte { get; set; }
    public List<Nullable<short>> Short { get; set; }
    public List<Nullable<ushort>> Ushort { get; set; }
    public List<Nullable<int>> Int { get; set; }
    public List<Nullable<uint>> Uint { get; set; }
    public List<Nullable<long>> Long { get; set; }
    public List<Nullable<ulong>> Ulong { get; set; }
    public List<Nullable<float>> Float { get; set; }
    public List<Nullable<double>> Double { get; set; }
    public List<Nullable<decimal>> Decimal { get; set; }
    public List<Nullable<char>> Char { get; set; }
    //public List<object> Object { get; set; }
    public List<string> String { get; set; }
    public List<Nullable<DateTime>> Datetime { get; set; }

    //public List<bool> Bool { get; set; }
    //to mange also 0/1
    public List<string> Bool { get; set; }
    private List<Nullable<bool>> Boolean
    {
        get
        {
            List<Nullable<bool>> tmp_b = new List<Nullable<bool>>();

            foreach (string tmp in Bool)
            {
                switch (tmp.ToUpper())
                {
                    case "TRUE":
                    case "1":
                        tmp_b.Add(true);
                        break;
                    case "FALSE":
                    case "0":
                        tmp_b.Add(false);
                        break;
                    default:
                        tmp_b.Add(null);
                        break;
                }
            }
            return tmp_b;
        }
    }

0
投票

> 所以我的问题是如何做到这一点?我必须启动到不同的系统吗?

从您的常规帐户注销,然后以

root
身份登录。 Root 的主目录传统上是 /root,位于 /home 之外。

然后确保所有用户进程都已停止 – 例如可能有一个“systemd --user”进程徘徊;使用

systemctl stop user@YourUID
停止它。 (使用
systemctl stop user-YourUID.slice
或仅使用
pkill -u YourName
杀死任何其他剩菜。)

> 也许有更简单的方法来恢复主页快照?

如果您可以从快照中cp -a恢复您需要的特定文件或目录,则不必首先

恢复整个快照。

$ sudo cp -av /snapshots/home_snap_1234/Projects ~/Projects.restored
(根据 

/snapshots

 的设置方式,您甚至可能不需要“sudo”。)

使用现代 GNU coreutils 'cp',这将生成引用链接而不是完整副本,并且不会占用额外空间(尽管如果您的 coreutils 版本早于 9.1,那么您需要添加

--reflink

 以确保这一点)。

© www.soinside.com 2019 - 2024. All rights reserved.