Zar E Ahmer
Zar E Ahmer

Reputation: 34370

Post int directly to web api without model class

I am new to C#. I tried to create a post service with using int. All get and post service are working fine.

But when I pass parameter to post service, it's always null. But after creating a class it works fine. Can we pass direct int to service or we must have to create a model class for it?

    [System.Web.Http.HttpPost]
    public IHttpActionResult GetUserByID(int id)
    {
        var user = userList.FirstOrDefault((p) => p.Id == id);
        if (user== null)
        {
            return NotFound();
        }
        return Ok(user);
    }

but it always send 0 . but when i create a class and add that int as attribute it works fine.

Working code

    [System.Web.Http.HttpPost]
    public IHttpActionResult GetUserByID(data id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        return Ok();
    }

   public class data
   {
       [Required]
       public int id { get; set; }
   }

Edit

are my header accurate?

enter image description here

Upvotes: 5

Views: 5729

Answers (2)

Send Data to Web Api by a Jquery Like Below :

function PostSth(fid){
  $.ajax({  
    url: apiBaseUrl + 'api/Controller/ActionMethod',  
    type: 'Post',  
    data:`'`+fid+`'`,
    contentType: "application/json; charset=utf-8",
    success: function (data) {         
        alert(data);

    },  
    error: function () {  
        alert('Error');  
    }  
 });
}

Don't Forget

data:`'`+fid+`'`,

above.

and do in the Code Behind Part :

public string ActionMethod([FromBody]int fid)
{
     string result = string.Empty;
     //TODO: Your Code

    return result;
}

Upvotes: 0

Matthew Cawley
Matthew Cawley

Reputation: 2818

I think you need to add [FromBody] to the parameter:

[System.Web.Http.HttpPost]
public IHttpActionResult GetUserByID([FromBody]int id)
{
    var user = userList.FirstOrDefault((p) => p.Id == id);
    if (user== null)
    {
        return NotFound();
    }
    return Ok(user);
}

According to the docs: Parameter Binding in ASP.NET Web API

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.
  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

It goes on to say: Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter

UPDATES - to get [HttpPost] working...

As @Shahbaz suggested below, make sure that you've got the Content-Type header set to application/json, otherwise you will get error message saying:

The request entity's media type 'text/plain' is not supported for this resource.

Also, make sure you're posting just the id in the Request Body e.g. 1, as opposed to posting the id wrapped in a JSON object as a key/value pair { "id": "1" }.

FINALLY - consider using [HttpGet] instead...

It's worth pointing out, because you are now just sending a single int to get a single record, even if you can get this working using [HttpPost], it's still probably best to change it to [HttpGet] which is semantically correct - you are getting a user record, and don't actually need to post anything at all. So something like this might be better:

[System.Web.Http.HttpGet]
[Route("api/users/{id}")]
public IHttpActionResult GetUserByID(int id)
{
    var user = userList.FirstOrDefault((p) => p.Id == id);
    if (user== null)
    {
        return NotFound();
    }
    return Ok(user);
}

Then put your id in the request URL, something like:

https://yourdomain/api/users/1

The above example makes use of Attribute Routing which can help you create your own custom URLs to target your own API Action Methods.

Upvotes: 7

Related Questions