2
votes

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;

    }
2
Do you have another method with name post and verb as httpget?Sateesh Pagolu
only other verb is // GET: api/Group [Route("api/Group/Get")] [HttpGet] public Array Get()oooo ooo

2 Answers

4
votes

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.
0
votes

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.