Web Api c# Get Query Sring from url - Asp.net - c#

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
}

Related

Postman won't POST to ASP.Net WebAPI 2 controller, but GET works

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

How to form a URL to access the webapi controller?

I would like to know how we will create a Route URL to access the above function. Error message comes stating that I cannot access the controller
[HttpGet]
[Route("api/TeacherData/ListTeachers/{SearchKey?}&{order?}")]
public List<Teacher> ListTeachers(string SearchKey = null, string order = null)
{
}
I know it's your API and your design, but following the REST API patterns we should stick to simple API URLs, something like api/teachers could be easier to understand by the consumers if they know that the endpoint uses the GET method.
About your actual question, you could change the code to use [FromQuery] to expect parameters that should come from the query string:
[HttpGet]
[Route("api/teachers")]
public List<Teacher> ListTeachers([FromQuery] string searchKey = null, [FromQuery] string order = null)
{
}
Then, from the consumer side, you could trigger this endpoint using the following URL:
GET http://myapi.com/api/teachers?searchKey=keyValue&order=orderValue
If you keep your URL structure it should something like this:
GET http://myapi.com/api/TeacherData/ListTeachers?searchKey=keyValue&order=orderValue

Put request is not working using postman to web api 2 c#

I have a method in Api as follows
[HttpPut]
[Route("UpdateTeacher")]
public IHttpActionResult UpdateTeacher(BusinessLayerTeacher Obj)
{
try
{
BusinessLayerTeacher obj = new BusinessLayerTeacher ();
string status = BusinessLayerObject.UpdateTeacher(TeacherObj);
return Ok(status);
}
catch
{
return NotFound();
}
}
Now in post man i am sending the put request to update the teacher object.
It is not triggering this updateTeacher() method.
You are instantiating a new BusinessLayerTeacher object inside the method, which looks suspect when you are already passing in BusinessLayerTeacher as a parameter.
Maybe the route mapping isn't working because you're not passing in the right data in the request body.
Maybe you should be using TeacherObj as the parameter type?
Have a review and give that a try, good luck :-)

Testing the web api that accepts JSON as input

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.

I need to pass a parameter from request header to the API controller action method. How can I?

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();

Categories