简体   繁体   English

尝试在本地C#web api中使用Postman PUT字符串,始终为null或失败

[英]Trying to PUT string with Postman in local C# web api, always null or fails

I currently have this WEB API running locally: 我目前在本地运行此WEB API:

// POST api/CsvParse
[HttpPut]
public void Put([FromBody]string value)
{
    if (string.IsNullOrEmpty(value))
        throw new Exception("Input is null or empty.");
}

I currently have it running locally, and am sending a string to the put using POSTMAN. 我目前在本地运行它,并使用POSTMAN将字符串发送到put。 I have selected the body tab, and have the string pasted into the raw body tab: 我选择了body选项卡,并将字符串粘贴到raw body选项卡中:

在此输入图像描述

It states that my text is unsupported, or when I add a break point the value is null or I get the error describing the format is incorrect. 它声明我的文本不受支持,或者当我添加断点时,值为null或我得到描述格式的错误不正确。

What am I doing wrong? 我究竟做错了什么?

Change the media type to x-www-form-urlencoded rather than multipart/form-data. 将媒体类型更改为x-www-form-urlencoded而不是multipart / form-data。

Also, WebAPI is particular about FromBody parameters. 此外,WebAPI特别关注FromBody参数。 http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/ http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

For you, I think this is the relevant part: 对你而言,我认为这是相关部分:

  1. [FromBody] parameters must be encoded as =value [FromBody]参数必须编码为= value

The final hurdle remaining is that Web API requires you to pass [FromBody] parameters in a particular format. 剩下的最后一个障碍是Web API要求您以特定格式传递[FromBody]参数。 That's the reason why our value parameter was null in the previous example even after we decorated the method's parameter with [FromBody]. 即使我们使用[FromBody]修饰方法的参数之后,这就是我们的值参数在前一个示例中为null的原因。

Instead of the fairly standard key=value encoding that most client- and server-side frameworks expect, Web API's model binder expects to find the [FromBody] values in the POST body without a key name at all. Web API的模型绑定器不需要大多数客户端和服务器端框架所期望的相当标准的key = value编码,而是希望在POST主体中找到[FromBody]值而根本没有关键名称。 In other words, instead of key=value, it's looking for =value. 换句话说,它代替key = value,它正在寻找= value。

This part is, by far, the most confusing part of sending primitive types into a Web API POST method. 到目前为止,这部分是将原始类型发送到Web API POST方法中最令人困惑的部分。 Not too bad once you understand it, but terribly unintuitive and not discoverable. 一旦你了解它就不会太糟糕,但非常不直观且不可发现。

That's because there is no media type formatter that can serialize a raw string into your model (your route parameter with [FromBody] attribute). 那是因为没有媒体类型格式化程序可以将原始字符串序列化到您的模型中(使用[FromBody]属性的路由参数)。

A quick and dirty workaround is to directly read the body of your request as a string: 快速而肮脏的解决方法是直接以字符串形式读取请求正文:

[HttpPut]
public async Task<HttpResponseMessage> Put(HttpRequestMessage request)
{
    var myCsv = await request.Content.ReadAsStringAsync();

    // do stuff with your string

    return new HttpResponseMessage(HttpStatusCode.OK);
}

As an alternative you could implement a custom media type formatter yourself, as per this answer . 作为替代方案,您可以自己实现自定义媒体类型格式化程序,根据此答案

Try adding a content type of text/plain 尝试添加text/plain的内容类型

在此输入图像描述

There is a similar Q&A here 还有一个类似的Q&A 在这里

I found that solution #1 worked for me as I was trying to PUT JSON containing the Key/Value pair. 我发现解决方案#1对我有用,因为我试图PUT包含Key / Value对的JSON。 So originally my JSON looked like this 所以最初我的JSON看起来像这样

{
    "subscriber": {
    "Id": "2",
    "subscriptions":[
        {
            "Name": "Subscription 1",
            "Id": "18",
            "IsSubscribed": false
        },
        {
            "Name": "Subscription 2",
            "Id": "19",
            "IsSubscribed": false
        },
        {
            "Name": "Subscription 3",
            "Id": "20",
            "IsSubscribed": false
        }
    ]
    }
}

But I modified it to become 但我修改它成为

{
    "Id": "2",
    "subscriptions":[
        {
            "Name": "Subscription 1",
            "Id": "18",
            "IsSubscribed": false
        },
        {
            "Name": "Subscription 2",
            "Id": "19",
            "IsSubscribed": false
        },
        {
            "Name": "Subscription 3",
            "Id": "20",
            "IsSubscribed": false
        }
    ]
}

And that worked. 这很有效。 My PUT request from Postman was recognised in my C# web api using [FromBody] 我使用[FromBody]在我的C#web api中识别出Postman的PUT请求

Just to add my bit, there is one more solution to pass primitives into a POST or a PUT method. 只是为了添加我的位,还有一种解决方案可以将原语传递给POST或PUT方法。 Just specify the model as JObject . 只需将模型指定为JObject ASP.Net core web api then binds incoming JSON object(containing primitives like string) into JObject model object. ASP.Net核心web api然后将传入的JSON对象(包含字符串等原语)绑定到JObject模型对象中。

Your code would look like this: 您的代码如下所示:

// POST api/CsvParse
[HttpPut]
public void Put([FromBody]JObject value)
{
    //access your string data
    string data = value[SPECIFY_KEY_HERE];

    if (string.IsNullOrEmpty(data))
        throw new Exception("Input is null or empty.");
}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM