如何将ASP.NET WebAPI参数放入body(POST)而不是URI中



我正在构建一个简单的API,以从DB中检索帐户的余额。

http://localhost:8080/v1/api/accounts/balance?accountBalance=DS-00001

但是,当我试图在动作中使用[从body]从身体中获取它

 [HttpPost]
    [ActionName("balance")]
    public string GetBalance([FromBody]string accountNumber)
    {
        var data = BusinessLayer.Api.AccountHolderApi.GetBalance(accountNumber);
        return data;
    }

我在Postman中遇到此错误

" message":"请求实体的媒体类型'multipart/form-data'不支持此资源。 " exceptionMessage":"没有媒体型formatter可以读取与媒体类型'multipart/form-data'的内容'字符串'的对象读取对象 " exceptytype":" system.net.http.unsupportedmediatiatypeexception", " stacktrace":"在System.net.http.httpcontentextensions.readasasync [t](httpContent content,type type,iEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)rn at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable 1 formatters,iformatterLogger formatterlogger formatterlogger,cancellationToken concellationToken(">

我确实在这里发现了与这个问题模糊的相似之处,但无法通过。绑定/参数绑定式载主 - web-api,但仍在此处说,在此处说,原始类型是使用[从body]属性,但仍然。

和我的路线

  config.Routes.MapHttpRoute("MobileBankingApi", "v1/api/{controller}/{action}");

在Postman主体> form-data I输入

key =帐户余额= DS-00001

我希望json响应

{" account_number":" CS-0000011"," Balace":7817.7}

我的邮递员输入可能是错误的,或者我没有为此做R& d,但是帮助新手仍然是您的荣幸。

谢谢。

从我从评论中看到的内容,您将数据发布为 { "accountNumber":"DS-10896" }

要在控制器中匹配它,您需要定义一个具有名为accountnumber的字符串参数的对象并从身体中读取。

首先,定义类

public class Account
{
    public string accountNumber { get; set; }
}

然后将其添加为身体参数

[HttpPost]
[ActionName("balance")]
public string GetBalance([FromBody]Account account)
{
    var data = BusinessLayer.Api.AccountHolderApi.GetBalance(account.accountNumber);
    return data;
}

然后,当您发布数据时,使用与您现在相同的JSON结构,那就是{ "accountNumber":"DS-10896" }

更新:

要返回带有您请求的值的对象,我只会在帐户类中添加第二个参数

public class Account
{
    public string accountNumber { get; set; }
    public int balance { get; set; }
}

然后将对象值填充在控制器方法

HttpPost]
[ActionName("balance")]
public IHttpActionResult GetBalance([FromBody]Account account)
{
    account.balance = BusinessLayer.Api.AccountHolderApi.GetBalance(account.accountNumber);
    return Ok(account);
}

Note :请查看IHTTPACTIONRESULT,它是Web API中的重要功能,以确定响应消息

尝试更改Postman中的身体类型以将数据发送为: "raw" JSON(application/json)而不是form-data

这是相关的方法指南:https://www.getpostman.com/docs/requests

最新更新