1
votes

I upgraded a webapi solution from 2.1 to 3.1.

My Startup.cs file contains:

public void ConfigureServices(IServiceCollection services)
{
   services.AddControllers();
   services.AddMvc().AddNewtonsoftJson();
..

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
   if (env.IsDevelopment())
   {
       app.UseDeveloperExceptionPage();
   }

   app.UseRouting();
   app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
..

My controller starts with:

[ApiController]
[Route("api/[controller]/[action]")]
public class MyFooController : Controller

and here is my action:

[HttpPost]
public string MyFooAction(string value)

So I call action from another easy solution with:

var param = new NameValueCollection();
param["value"] = "3";
using (var client = new WebClient())
{
    var data = client.UploadValues(url, "POST", param);

In debug, the call gets the action route but value=null always. I also tried with [FromBody] but it's the same.

I read in 3.1 would be prefer inherint controller from ControllerBase class but I have many action that return Json(obj) and that is not present in ControllerBase class but only in Contreller class: is this the problem?

Thanks in advance.

1
Hi @CodeIT, any updates about this case? Have you resolved the issue with the solution I shared?Fei Han
Hi Fei, sorry... not practice... Have I well done now?CodeIT

1 Answers

0
votes

var data = client.UploadValues(url, "POST", param);

the call gets the action route but value=null always

Using WebClient.UploadValues method to post the value(s) to the server, you can try to apply [FromForm] attribute to your action parameter, as below.

[HttpPost]
public string MyFooAction([FromForm]string value)
{

    //...

Test Result

enter image description here

Besides, you can achieve same requirement using WebClient.UploadString method to post data through request body.

using (var client = new WebClient())
{
    client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
    var data = client.UploadString(url, "POST", "3");
    //...
}

Action method

[HttpPost]
public string MyFooAction([FromBody]string value)
{

    //...

Test Result

enter image description here