How to form a URL to access the webapi controller? - c#

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

Related

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

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
}

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.

How to route Optional URI parameters to API Controller functions

I am trying to set up an Asp.Net forms site with an API.
I have succeeded in adding in selective authentication, so that pages starting "\api\" do not get redirected, but instead challenge for basic authentication.
I am now trying to use MS Web Api 2 to do the API routing.
The idea is to be as RESTful as possible. I have a resource, a TradableItem, and initially I would want to allow API users to use HTTP GET in one of two ways.
If the API user passes no item key, the user receives a list of possible item keys
["ABC","DEF"...]
If the API user passes an item key as part of the URI, eg "/api/tradables/abc", a representation of the TradableItem is returned for the one with the key=ABC. (To my understanding, this is standard REST behaviour).
In Global.ASAX's Application_Start() function I have a route map like so...
RouteTable.Routes.MapHttpRoute(
name: "TradableItemVerbs",
routeTemplate: "api/tradables/{item}",
defaults: new { item = System.Web.Http.RouteParameter.Optional, controller = "Tradable" });
The TradableController.cs file looks like this...
public class TradableController : ApiController
{
private static CustomLog logger = new CustomLog("TradableController");
// GET api/<controller>
public IEnumerable<string> GetKeys()
{
var prefix = "GetKeys() - ";
string msg = "";
msg = "Function called, returning list of tradable pkeys...";
logger.Debug(prefix + msg);
// Get a list of tradable items
return TradableManager.GetTradablePkeys();
}
// GET api/<controller>/<pkey>
public string GetTradable(string pkey)
{
string msg = string.Format("Would get Tradable data for key: >{0}<", pkey);
return msg;
}
}
The problem is that only the GetKeys() function fires, whether I call GET to "/api/tradables" or "/api/tradables/abc".
For reference, using VS2015 Community, IIS 7.5, targeting .Net 4.6.1. I used Rick Strahl's blog as a guide on this (among other sources).
http://weblog.west-wind.com/posts/2012/Aug/21/An-Introduction-to-ASPNET-Web-API#HTTPVerbRouting
please, change the name of your param to item (because, this is the name define in the routes):
public string GetTradable(string item)
{
....
}
or when you call the method be explicit with the parameter name: /api/tradables?pkey=abc

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

Routing POST with Query Parameters in MVC Web API

In a Web Apì project, I would like to use something like:
POST/mycontroller/1
but also POST/mycontroller/1?user=john
It is easy with GET because the framework routes correctly to each function. However, when I use POST, it does not work. I have 2 POST functions in the same controller. For example:
void Post(int id, string content)
and
void Post(int id, string content, string user)
I would hope when I call POST/mycontroller/1?user=john, the framework routes to Post(int id, string content, string user)
I know that I can use binding models, doing a model class and one unique POST function, but it is a mess because I have many functions and I would like to be able to use the query parameters to route the correct function.
Is it possible?
Try declaring parameter with [FromBody] and [FromUri] attribute like this:
public string Post(int id, [FromBody]string content, [FromUri] string user)
{
return "content = " + content + "user = " + user;
}
With above code I was able to call
/Test/1?user=Ryan
Request body
"Test Body"
and the result is:
"content = Test Bodyuser = Ryan"
Hope this helps.

Categories