sparkysword sparkysword - 1 year ago 142
C# Question

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

I currently have this WEB API running locally:

// POST api/CsvParse
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. I have selected the body tab, and have the string pasted into the raw body tab:

enter image description here

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.

What am I doing wrong?

Answer Source

That's because there is no media type formatter that can serialize a raw string into your model (your route parameter with [FromBody] attribute).

A quick and dirty workaround is to directly read the body of your request as a string:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download