2

I'm really struggling with making a basic post request in a url to support a tutorial on web api.

I want to do something like this in browser: http://localhost:59445/api/group/post/?newvalue=test and get the post to register. However I don't seem to be able to form the request correctly. What is the correct way to do this?

The error I receive is:

{"Message":"The request is invalid.","MessageDetail":"The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'twin_groupapi.Controllers.GroupController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."}

my model:

    public class Group  
    {
     public Int32 GroupID { get; set; }
     public Int32 SchoolID { get; set; }
     public string GroupName { get; set; }
    }

routing:

public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

controller:

    //[Route("api/Group/Post")]
    [HttpPost]
    public void Post([FromUri] string NewValue)
    {

        string newstring = NewValue;

    }
Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
oooo ooo
  • 314
  • 1
  • 2
  • 11

2 Answers2

6

Hitting a URL in your browser will only do a GET request.

You can either:

  • create a simple <form> with its method set to POST and form inputs to enter the values you want to send (like NewValue), OR
  • write some JavaScript to create an AJAX POST request using your favorite framework, OR
  • Use a tool like Postman to set up a POST request, invoke it, and examine the results.
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
2

The error message is most likely coming from your Get() method.

As @StriplingWarrior said you are making a GET request while the method is marked as [HttpPost]. You can see this if you use developer tools in your browser (F12 in most modern browsers to active them).

Have a look at How do I manually fire HTTP POST requests with Firefox or Chrome?

Note: the c# convention for parameter names is camelCase with first letter being common, not capital, e.g. string newValue.

Community
  • 1
  • 1
tymtam
  • 31,798
  • 8
  • 86
  • 126
  • To make this concrete from the link above, read up on the Fetch API as perhaps the simplest approach. So if you want to do a POST from the browser, just type something like the following in the browser console: `fetch('http://localhost:59445/api/group/post/?newvalue=test',{ method: 'POST'})` – Tawab Wakil Jun 04 '22 at 17:41