I Have a C# WinForms application and in a form I want to consume (Get) some data from an ASP Web API application.
in Web API I have a controller named Session inside this controller I have two methods as shown below :
public int Create()
{
Random random = new Random();
int New_ID = random.Next();
return New_ID ;
}
public string Get()
{
return "Catch this data";
}
So the problem is when I use browser URL (For testing) to access to controller (Session)
URL : http://localhost:52626/api/Session
I got
And when I want to access to controller (Session) especially Create Function
URL : http://localhost:52626/api/Session/Create
I got
The global question is how can I create my own methods and access to it without depending on Get ?
The browser always fires a GET. Web-API by default selects the method to be called using the HTTP verb (GET in your case) of request. Hence it always lands in "Get" method. To make Web-API point to your method you need to define a route. Use below:
[Route("api/session/Create")]
[HttpGet]
public int Create()
{
Random random = new Random();
int New_ID = random.Next();
return New_ID;
}
To better understand route based selection, read this : https://learn.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/routing-and-action-selection
Related
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
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
}
Given a controller Proxy and an action of GetInformation. I want to be able to call the method GetInformation of the Users controller. Both the WebAPI controllers are in the same project but direct calls like
var controller = new UsersController();
return controller.GetInformation(request);
Doesn't work.
The signature is:
public HttpResponseMessage GetInformation(InformationRequest request)
I do not want to do a full redirect response as I do not want the UserController route exposed externally. This needs to be an internal only call.
For those wanting to solve this API to API method in different controllers, we have found a solution that works. The initial attempt was close, just missing a few things.
var controller = new UserAccountController
{
Request = new HttpRequestMessage(HttpMethod.Post, Request.RequestUri.AbsoluteUri.Replace("/current/route", "/route/to_call"))
};
controller.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration();
return controller.GetInformation(request);
In doing this it allows construction of the target controller and direct invocation of the method desired. The biggest complexity here is the Uri adjustment.
You should do something like this in your UsersController
public HttpResponseMessage GetInformation(InformationRequest request)
{
HttpResponseMessage resp ;
resp = UserBusinessLogic.GetInformation(request) ;
return resp ;
}
and from your ProxyController you can resuse that "UserBusinessLogic" method to obtain the same information using the same code snippet.
Another way can be:
IQueryable<Users> GetInformation()
without using the IHttpActionResult return type. Your method will still remain an Http GET method and then call it in the same way as you call any class method.
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'm using asp.net mvc,
I have a POST Method that called from an outside service(differnet domain) and i want when it called to get data from my site.
Before the method was called I tried to save that data in Session object and in a Cookie,
But the data is not there.
Maybe it could be because the post request sent from a different domain?
What am I doing wrong?
[HttpPost]
public ActionResult Callback(Callback callback)
{
Not Working ->
var userMail = HttpContext.Request.Cookies.Get("Current")["UserMail"];
}
public ActionResult SomeSitePage()
{
var cookie = new HttpCookie("Current");
var userMail = (Session["user"] as ApplicationUser).Email;
cookie["UserMail"] = userMail;
HttpContext.Response.Cookies.Add(cookie);
}
Thanks.
Apparently If a post method is called from another domain,
saving data in session or cookies does not count,
I needed to save it in the database first and then pull it out in the post method.