WebAPI Selfhost:Can';t将多个参数绑定到请求';的内容

本文关键字:绑定 请求 参数 Selfhost Can WebAPI | 更新日期: 2023-09-27 17:59:45

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

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

如果我只有A或B,那就太好了。

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

WebAPI Selfhost:Can';t将多个参数绑定到请求';的内容

我认为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
    }

希望能有所帮助。

尝试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)

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

{"消息":"出现错误&";,"异常消息":"无法将多个参数('userName'和'passWord')绑定到请求的内容&";,"例外类型":"System.InvalidOperationException";,"StackTrace":"位于System.Web.Http.Controllers.HttpActionBinding.ExecuteBindingAsync(HttpActionContext actionContext,CancellationToken cancellionToken)''r''n位于System.Web.Http.Controllers.ActionFilterResult.d_5.MoveNext()''r''n-从引发异常的前一位置开始的堆栈跟踪结束---''r''n位于的System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)''r''nSystem.Web.Http.Dispatcher.HttpControllerDispatcher.d__15.MoveNext()上的System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)''r''n;}

我能够使用以下代码解决它

// 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;
            
        }
    }
}

我编写了一个泛型类,以列表形式管理所有数据类型,并发送所有内容。然后在你身上我可以,例如:

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