Post String to ASP.NET Web API Application - Returns Null

POST string to ASP.NET Web Api application - returns null

You seem to have used some [Authorize] attribute on your Web API controller action and I don't see how this is relevant to your question.

So, let's get into practice. Here's a how a trivial Web API controller might look like:

public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}

and a consumer for that matter:

class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}

You will undoubtedly notice the [FromBody] decoration of the Web API controller attribute as well as the = prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.

As far as the [Authorize] attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post that I wrote on this topic interesting to get you started.

And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.

Web api post - passed string value is null at server side

It's null because the body couldn't be parsed as a string. The content type is application/x-www-form-urlencoded instead of text/plain.

You may want to rethink using a string anyway if your client is sending json, you should accept application/json on the server and let the framework parse it for you.

[HttpPost]
public void Post(MyObject value)
{
var msg = value.Message;
}

public class MyObject
{
public string Message { get; set; }
}

Client Side:

var cstrJson = new StringContent("{'Message' : 'hello'}", System.Text.Encoding.Unicode, "application/json");

var result = await client1.PostAsync("http://localhost:68888/api/myApi/", cstrJson);

Post parameter is always null

Since you have only one parameter, you could try decorating it with the [FromBody] attribute, or change the method to accept a DTO with value as a property, as I suggested here: MVC4 RC WebApi parameter binding

UPDATE: The official ASP.NET site was updated today with an excellent explanation: https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-1

In a nutshell, when sending a single simple type in the body, send just the value prefixed with an equal sign (=), e.g. body:

=test

ASP.NET Web API receives a null as parameter in POST when called from R

Try setting the Content-Type header to "application/json" in your R request. PostAsJsonAsync is likely doing this for you in your C# client. Content-Type tells the endpoint what kind of data you're sending. Accept says what you expect in response.

FromBody string parameter is giving null

By declaring the jsonString parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class

public class MyModel
{
public string Key {get; set;}
}

[Route("Edit/Test")]
[HttpPost]
public void Test(int id, [FromBody] MyModel model)
{
... model.Key....
}

and a sent JSON like

{
key: "value"
}

Of course you can skip the model binding and retrieve the provided data directly by accessing HttpContext.Request in the controller. The HttpContext.Request.Body property gives you the content stream or you can access the form data via HttpContext.Request.Forms.

I personally prefer the model binding because of the type safety.

Why returning null does nothing in web api project?

This is a behavior newly introduced in .Net Core 3 where if the Action method returns null, it just sends a 204 response which represents No Content. If you desire to return null from an action method, you can override this behavior by using below code block inside Startup.cs file which removes the corressponding Output formatter and you will get null returned from the API response.

services.AddControllers(options =>
{
options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});

asp.net webapi 2 post parameter is always null

Do you always send the same parameters? If so, could you create a static object instead of using a dynamic one? Something like an EventRequest that you pass in instead?

public class EventRequest
{
public int CheckinCount { get; set; }
public int EventId { get; set; }
public int OrderNo { get; set; }
}

Your Post action then becomes:

public IHttpActionResult Post(EventRequest request) {
// do something with request
return Ok();
}

How to handle undefined or null in ASP.NET Core web API from frontend React.js?

You can use "all" in productIds for example:

/api/Account/55/all/files

Or you can also change the structure of the api for example:

/api/Account/files/{accountID}/{productIds}

And productIds can be "all" or Number

or you can use queryParams for productIds like:

/api/Account/{accountID}/files?productIds=Number

for example:

/api/Account/20/files?productIds=4

and when productIds not sended, you send all files for specific accountID

1./api/Account/20/files

Or

2./api/Account/20/files?productIds=all



Related Topics



Leave a reply



Submit