I am creating a web api that needs to accept JSON as input that is sent by the called client side application. Below is the Code
public class SetNameController : ApiController
{
[HttpPost]
public async Task<IHttpActionResult> Get([FromBody] CodeDTO.RootObject bCode)
{
string Bar_Code = bCode.Barcode.ToString();
if (Bar_Code == "" || Bar_Code == null)
{
....
return OK(response)
}
Here I am not sure How the client application call this Web API, the URL can be just like http://localhost:41594/api/SetName can it accept the JSON? Also can I test this using PostMan or Fiddler?
Specify the following:
Method: POST
Header: Content Type
Then, provide the payload json data in Body as raw:
Also, change the name of the action Get which might cause confusion. If you still cannot hit your api, you can use route urls by decorating the action with [Route('yourURL')] attribute and change that accordingly in postman.
Related
I can't seem to get my webapi to work in PostMan and it gives me a 404 when POSTing, but works only when using GET (even though the api specifically set to accept only POSTs! - go figure!)
Here's the controller code (that works) - NOTE: I can't use formdata as this is dotnet fw 4.72
[Route("api/GetProfile")]
[HttpPost]
public async Task<IHttpActionResult> GetProfile(string UserId)
{
var retval = new Profile();
if (UserId != null)
{
if (await dbv.IsValidUserIdAsync(UserId))
{
retval = await profile_Data.GetProfileAsync(UserId);
}
}
return Ok(retval);
}
The code works fine for GET (even though it's set to accept POST!), which it shouldn't.
In PostMan, the URI is
https://localhost:44371/api/GetProfile
The route is 100% correct!
On the Body tab, it is set to RAW and the following JSON is inside
{"UserId" : "69d40311-f9e0-4499-82ea-959949fc34fe"}
The parameter is 100% correct!
The error when attempting to POST is
{
"Message": "No HTTP resource was found that matches the request URI 'https://localhost:44371/api/GetProfile'.",
"MessageDetail": "No action was found on the controller 'Accounts' that matches the request."
}
If I put the parameters in the querystring, it works (even though the controller is set to accept POST).
If I change the controller to GET and PostMan to GET (and set the parameters in params), it works.
Is PostMan not compatible with ASP.Net webapi 2.0 ?
Why would GET work and POST not work? Makes no sense?
Try to set Content-Type application/json on postman and in your controller's POST method add the attribute FromBody
[FromBody] isn't inferred for simple types such as string or int. Therefore, the [FromBody] attribute should be used for simple types when that functionality is needed.
[Route("api/GetProfile")]
[HttpPost]
public async Task<IHttpActionResult> GetProfile([FromBody] string UserId)
{
var retval = new Profile();
if (UserId != null)
{
if (await dbv.IsValidUserIdAsync(UserId))
{
retval = await profile_Data.GetProfileAsync(UserId);
}
}
return Ok(retval);
}
Also consider to return CreatedAtAction or CreatedAtRoute instead of Ok
I have written web api in which it is returning/producing json response. Below is the code for the same.
[HttpGet]
[Route("someapi/myclassdata")]
[Produces("application/json")]
public MyClassData GetMyClassData(int ID, int isdownload)
{
myclassdata = myclassdataBL.GetMyClassData(ID);
return myclassdata;
//**Commented Code**
//if(isdownload==1)
//{
//download file
//}
//else
//{
// send response
//}
}
Till now it is working fine. Now I want to create and download the file based on value in 'isDownload' parameter.
So after getting the data if files needs to be downloaded I want to download the file otherwise I will send the json response.
So, my question is can we send json reponse or download the file in same web api method.
Any help on this appreciated!
Yes, this is easily achievable. Rather than returning MyClassData explicitly like that, you can return an IActionResult, like this:
public IActionResult GetMyClassData(int ID, int isdownload)
{
myclassdata = myclassdataBL.GetMyClassData(ID);
if (isDownload == 1)
return File(...);
return Ok(myclassdata);
}
Both File(...) and Ok(...) return an IActionResult, which allows for the dynamism you're asking for here.
Note: You can also just return Json(myclassdata) if you want to force JSON, but by default this will be JSON anyway and is more flexible with e.g. content-negotiation.
See Controller action return types in ASP.NET Core Web API for more details.
I got a url where it's method is post but I want to pass some paramets by get method, I am using c# MVC asp.net
as the follow link
http://site/api/user/seach/?value=here&value2=here2
I am trying to get this using
public IHttpActionResult Get()
{
var queryString = this.Request.GetQueryNameValuePairs();
}
And I already tried to use
string p = Request.QueryString["value"];
But it seems to work only in controller base exteds
Is there some way to get this value get in a post method ?
Sounds like you'd like to use the POST verb but send data through querystring, in that case you can:
public IHttpActionResult Post([FromUri]string value)
{
// do whatever you need to do here
}
I have written asp.net web-api project with following api-s:
Controller Method: Uri:
GetAllItems: /api/items (works)
GetItem(int id) /api/items/id (works)
and
GetListOfItem(IEnumerable<Items> items) /api/items/List of items (doesn't work)
The function is similar to this (don't care about logic)
public IHttpActionResult GetByArray(IEnumerable<Book> bks)
{
var returnItems = items.Select(it => it).Where(it => it.Price < bks.ElementAt(0).Price || it.Price < bks.ElementAt(1).Price);
if (returnItems == null)
return NotFound();
else
{
return Ok(returnItems);
}
}
I am using postman to send requests and following requests works correct
http://localhost:50336/api/items/
http://localhost:50336/api/items/100
but not
http://localhost:50336/api/items/[{"Owner":"MySelf","Name":"C","Price":151},{"Owner":"Another","Name":"C++","Price":151}]
How should i format the last request where i have a list of items in json format in order to get it works?
You want to decorate your method with a HttpPostAttribute and FromBodyAttribute:
[HttpPost]
public IHttpActionResult GetByArray([FromBody]IEnumerable<Book> bks)
{
}
Then send the json as post body.
Your Postman shoud look like this:
Specifically for
GetListOfItem(IEnumerable<Items> items)
[FromBody] is definitely best option.
In case you are using primitive types you can do following:
GetListOfItem([FromUri] int[] itemIds)
And send request as:
/GetListOfItem?itemIds=1&itemIds=2&itemIds=3
I am using WEB API 2.0 for REST Service development and I need to pass a parameter from request header to the API controller action method. How can I?
By default API controller is reading the parameters from request body.
How can I make it read parameter from request header?
[HttpPost]
[Route("abc")]
public IHttpActionResult abcMethod(string s)
{
//some code
}
I want the above abcMethod to read it's parameter from request header.
Pls suggest.
How about this...
IEnumerable<string> headerValues = request.Headers.GetValues("MyCustomID");
var id = headerValues.FirstOrDefault();
I'm still new to the Web API 2, but I usually do
string variale = this.Request.Headers.GetValues("HeaderParameter").First();
Any of the FirstOrDefault, Single, SingleOrDefault() or anything of the like will work.
Also, Lambda works as well:
string variable = this.Request.Headers.First(header => header.Key == "Parameter").Value.FirstOrDefault();