Method returns multiple object - c#

I have a MVC 4 project which consumes services from a web api 1 project .
Here i need to have a service method where i pass an id and a string named action based on the action
the service should go and fetch data from the table. Here i will have different cases based on the actions.
So if my action is person it should go to person table and based on the id passed it should return LIST
IF action is email it should fetch data from the Email table based on the id passed and should return LIST
Is it possible to achieve from single method as my return type will be different in each cases? If so what will be my return type of the method?
public Email GetEmail(int id)
{
Email email = db.Emails.Find(id);
if (email == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return email;
}
public List<Email> GetEmailByPerson(int personid)
{
List<Email> email = db.Emails.Where(n => n.PersonID == personid).ToList();
if (email == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return email;
}
public Person GetPerson(int id)
{
Person person = db.Persons.Find(id);
return person;
}
My get service call always call the same method
Modified as below based on the comments
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Code for controller action is:
[ActionName=EmailsByPersonID]
public IEnumerable<Email> GetEmailsByPersonID(int personid)
{
var emails = db.Emails.Where(n => n.Personid == personid).ToList();
if (emails == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return emails.AsEnumerable();
}
I have made these changes in the web api.config file and decorated my method with action name : EmailByPerson and the service call is http://localhost:XXXX/ActionApi/Email/EmailsByPersonID/1

I don't like this approach, but you don't ask us to make opinions about it but a specific question. And the answer to the question is YES it's possible.
You can use HttpResponseMessage for this purpose:
public HttpResponseMessage GetXx(string type, int id)
{
switch(type)
{
case "xx":
Type1 obj1 = <your logic>;
return Request.CreateResponse(HttpStatusCode.OK, obj1);
case "yy":
....
}

with this template -
public class MyController : ApiController
{
public string GetName(string id)
{
return id;
}
public string GetNameById(string id)
{
return id;
}
}
GlobalConfiguration.Configuration.Routes.MapHttpRoute
("default","api/{controller}/{action}/{id}",new { id = RouteParameter.Optional });
then make the calls to api like -
http://localhost:port/api/My/GetName/12
http://localhost:port/api/My/GetNameById/12
works for me atleast. :)
UPDATE
You could also do it like this -
public class CustomActionInvoker : ApiControllerActionSelector
{
public override HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
var routeData = (string)controllerContext.RouteData.Values["optional"];
if (!string.IsNullOrWhiteSpace(routeData))
{
var actionInfo = controllerContext.ControllerDescriptor.ControllerType
.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly).ToList();
var methodInfo = actionInfo.Where(a => a.Name.Contains(routeData)).FirstOrDefault();
if (methodInfo != null)
{
return new ReflectedHttpActionDescriptor(controllerContext.ControllerDescriptor, methodInfo);
}
}
return base.SelectAction(controllerContext);
}
}
In the config -
GlobalConfiguration.Configuration.Routes.MapHttpRoute("default", "api/{controller}/{optional}/{id}", new { id = RouteParameter.Optional });
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionSelector), new CustomActionInvoker());
And change the api call to -
http://localhost:port/api/My/Email/12
May be the previous example follows exactly this approach out of the box.

There are several ways to fix this.
1. You can use [RoutePrefix("api/Service")] for your controller and [Route("User")] and [Route("Email")] ,
you should be able too call your web api
api/service/user (GET,POST,PUT,Delete) ,
same thing goes with your Email as well
2. you can create IModel/IResult/SuperClass for your User/Email, and your web api method would be like IEnumerable<IModel> Get(string entityType) or
IModel Get(string entityType,int id)
Hope this will work.

Related

Getting error while calling WebApi

I am trying to create an API and trying to access it via chrome, expecting it to return the list of Items
public class ProductController : ApiController
{
Product product = new Product();
List<Product> productList = new List<Product>();
[HttpGet]
public HttpResponseMessage GetTheProduct(int id)
{
this.productList.Add(new Product {Id = 111,Name= "sandeep" });
return Request.CreateResponse(HttpStatusCode.OK, this.productList.FirstOrDefault(p => p.Id == 111));
}
}
I have not added route so wanna run it using default route but when i am running it, am getting
No HTTP resource was found that matches the request
URI 'http://localhost:65098/api/GetTheProduct()'.
No type was found that matches the controller named
'GetTheProduct()'.
Suggest me what all things are required to make it work.
If using default routes then configuration may look like this
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This would mean that routing is using convention-based routing with the following route template "api/{controller}/{id}"
Your controller in its current state is not following the convention. This results in requests not being matched in the route tables which result in the Not Found issues being experienced.
Refactor the controller to follow the convention
public class ProductsController : ApiController {
List<Product> productList = new List<Product>();
public ProductsController() {
this.productList.Add(new Product { Id = 111, Name = "sandeep 1" });
this.productList.Add(new Product { Id = 112, Name = "sandeep 2" });
this.productList.Add(new Product { Id = 113, Name = "sandeep 3" });
}
//Matched GET api/products
[HttpGet]
public IHttpActionResult Get() {
return Ok(productList);
}
//Matched GET api/products/111
[HttpGet]
public IHttpActionResult Get(int id) {
var product = productList.FirstOrDefault(p => p.Id == id));
if(product == null)
return NotFound();
return Ok(product);
}
}
Finally based on the route template configured then the controller expects a request that looks like
http://localhost:65098/api/products/111.
To get a single product that matches the provided id if it exists.
Reference Routing in ASP.NET Web API

GET verb not calling the correct action

So I scraped this controller code directly out of the MS .NET tutorials and it works fine:
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public IHttpActionResult GetProduct(int id)
{
Console.WriteLine("id = " + id);
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
}
In the same namespace I have created 2 of my own controllers and both display the same problem - only the first action (GetAll*()) responds to a GET, the second action (GetVehicle()) does not and when set by itself and decorated with [HttpGet] errors out with:
{
"Message": "The requested resource does not support http method 'GET'."
}
This controller seems identical to the product controller above:
public class VehiclesController : ApiController
{
Vehicle[] vehicles = new Vehicle[]
{
new Vehicle { Code = 1, Type = "type1", BumperID = "H0002" },
new Vehicle { Code = 2, Type = "type2", BumperID = "T0016" }
};
public IEnumerable<Vehicle> GetAllVehicles()
{
Console.WriteLine("GetAllVehicles()");
return vehicles;
}
public IHttpActionResult GetVehicle(int code)
{
Console.WriteLine("GetVehicle() code = " + code);
var vehicle = vehicles.FirstOrDefault((v) => v.Code == code);
if (vehicle == null)
{
return NotFound();
}
return Ok(vehicle);
}
}
but only the first action gets called. What am I missing? Same exact issue with a separate SecurityController. Pretty new to .NET.....
Self-hosting route maps added:
public void Configuration(IAppBuilder app)
{
// Configure Web API for self-host.
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
app.UseWebApi(config);
}
With the above code,
http://localhost:8080/api/vehicles
works, but
http://localhost:8080/api/vehicles/1
does not.
Anyone getting here via search Jeffrey Rennie's answer below is correct - the id in {id} is literal.
Try renaming GetVehicle()'s argument from code to id. It's related to Anthony Liriano's answer. The default routing pattern expects a argument named id.
You're missing the Route and Verb Attribute. This requires that you're using the System.Web.Http library. You can find more information on Attribute Routing in ASP.NET Web API 2
[HttpGet, Route("api/your/route/here")]
public IHttpActionResult GetVehicle(int code)
{
Console.WriteLine("GetVehicle() code = " + code);
var vehicle = vehicles.FirstOrDefault((v) => v.Code == code);
if (vehicle == null)
{
return NotFound();
}
return Ok(vehicle);
}
Or decorate your api endpoint as such like
[HttpGet("{code}/GetVehicleById")]
public IHttpActionResult GetVehicle(int code)
{
Console.WriteLine("GetVehicle() code = " + code);
var vehicle = vehicles.FirstOrDefault((v) => v.Code == code);
if (vehicle == null)
{
return NotFound();
}
return Ok(vehicle);
}
Your api endpoint call would be then
api/vehicles/123/GetVehicleById

ASP.Net Web api url is not working

I am new in web api.
i am sure i am doing something wrong for which my action is not getting called.
this is my action
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
when i am calling this action this way http://localhost:38762/api/customer/GetCustomersByCountry/Germany
the error is thrown, and error message is
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost:38762/api/customer/GetCustomersByCountry/Germany'.","MessageDetail":"No
action was found on the controller 'Customer' that matches the
request."}
tell me where i made the mistake ? thanks
Web config routes are
config.Routes.MapHttpRoute(
name: "WithActionApi",
routeTemplate: "api/{controller}/{action}/{customerID}"
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
EDIT : Full code added
public class CustomerController : ApiController
{
static readonly ICustomerRepository repository = new CustomerRepository();
public IEnumerable<Customer> GetAllCustomers()
{
return repository.GetAll();
}
public Customer GetCustomer(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return customer;
}
//[ActionName("GetCustomersByCountry")]
public IEnumerable<Customer> GetCustomersByCountry(string country)
{
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
public HttpResponseMessage PostCustomer(Customer customer)
{
customer = repository.Add(customer);
var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
response.Headers.Location = new Uri(uri);
return response;
}
public void PutProduct(string customerID, Customer customer)
{
customer.CustomerID = customerID;
if (!repository.Update(customer))
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
}
public void DeleteProduct(string customerID)
{
Customer customer = repository.Get(customerID);
if (customer == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
repository.Remove(customerID);
}
}
just tell me when controller will have multiple get whose parameter name is different then how could i handle the situation.
thanks
Given CustomerController like
public class CustomerController : ApiController {
[HttpGet]
public IEnumerable<Customer> GetCustomersByCountry(string country) {
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
}
a convention-based route can look like this
config.Routes.MapHttpRoute(
name: "CustomerApi",
routeTemplate: "api/customer/{action}/{countryId}",
default: new { controller = "Customer"}
);
which will map http://localhost:38762/api/customer/GetCustomersByCountry/Germany
The problem with your route is that your parameter name in the route template does not match.
Another option could be to use attribute routing
Attribute Routing in ASP.NET Web API 2
[RoutePrefix("api/customer")]
public class CustomerController : ApiController {
//GET api/customer/country/germany
[HttpGet, Route("country/{country}")]
public IEnumerable<Customer> GetCustomersByCountry(string country) {
return repository.GetAll().Where(
c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
}
}
with this configuration
public static class WebApiConfig {
public static void Register(HttpConfiguration config) {
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
}
Remove "Get" from the action in the url. Just keep CustomersByCountry instead of GetCustomersByCountry. So the url should be http://localhost:38762/api/customer/CustomersByCountry/Germany.

Multiple actions were found that match the request [duplicate]

This question already has answers here:
Multiple actions were found that match the request in Web Api
(18 answers)
Closed 5 years ago.
I have read a lot of questions about routing and controllers, but I simply can't find what I'm looking for. I have this controller which has this structure:
Update: Included full class source.
public class LocationsController : ApiController
{
private readonly IUnitOfWork _unitOfWork;
public LocationsController(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
// GET /api/locations/id
public Location Get(Guid id)
{
return this.QueryById<Location>(id, _unitOfWork);
}
// GET /api/locations
public IQueryable<Location> Get()
{
return this.Query<Location>(_unitOfWork);
}
// POST /api/locations
public HttpResponseMessage Post(Location location)
{
var id = _unitOfWork.CurrentSession.Save(location);
_unitOfWork.Commit();
var response = Request.CreateResponse<Location>(HttpStatusCode.Created, location);
response.Headers.Location = new Uri(Request.RequestUri, Url.Route(null, new { id }));
return response;
}
// PUT /api/locations
public Location Put(Location location)
{
var existingLocation = _unitOfWork.CurrentSession.Query<Location>().SingleOrDefault(x => x.Id == location.Id);
//check to ensure update can occur
if (existingLocation == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
//merge detached entity into session
_unitOfWork.CurrentSession.Merge(location);
_unitOfWork.Commit();
return location;
}
// DELETE /api/locations/5
public HttpResponseMessage Delete(Guid id)
{
var existingLocation = _unitOfWork.CurrentSession.Query<Location>().SingleOrDefault(x => x.Id == id);
//check to ensure delete can occur
if (existingLocation != null)
{
_unitOfWork.CurrentSession.Delete(existingLocation);
_unitOfWork.Commit();
}
return new HttpResponseMessage(HttpStatusCode.NoContent);
}
// rpc/locations
public HttpResponseMessage Dummy()
{
// I use it to generate some random data to fill the database in a easy fashion
Location location = new Location();
location.Latitude = RandomData.Number.GetRandomDouble(-90, 90);
location.Longitude = RandomData.Number.GetRandomDouble(-180, 180);
location.Name = RandomData.LoremIpsum.GetSentence(4, false);
var id = _unitOfWork.CurrentSession.Save(location);
_unitOfWork.Commit();
var response = Request.CreateResponse<Location>(HttpStatusCode.Created, location);
response.Headers.Location = new Uri(Request.RequestUri, Url.Route(null, new { id }));
return response;
}
}
And my routes definition (Global.asax):
public static void RegisterRoutes(RouteCollection routes)
{
// Default route
routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// A route that enables RPC requests
routes.MapHttpRoute(
name: "RpcApi",
routeTemplate: "rpc/{controller}/{action}",
defaults: new { action = "Get" }
);
}
So far if I hit the browser with:
[baseaddress]/locations/s0m3-gu1d-g0e5-hee5eeeee // It works
[baseaddress]/locations/ // Multiple results found
[baseaddress]/rpc/locations/dummy // It works
The strangest thing is that this used to work, until I messed up with my NuGet while performing some updates. What am I missing here?
Verbs starting with GET, POST, PUT or delete would be automapped to the first route and my dummy test method would be called via rpc, which would fall into the second route.
The error that is thrown is InvalidOperationException with message
Multiple actions were found that match the request:
System.Linq.IQueryable`1[Myproject.Domain.Location] Get() on type Myproject.Webservices.Controllers.LocationsController
System.Net.Http.HttpResponseMessage Dummy() on type Myproject.Webservices.Controllers.LocationsController
Any ideas?
The problem is in the order that the routes are loaded. If they are like this:
// A route that enables RPC requests
routes.MapHttpRoute(
name: "RpcApi",
routeTemplate: "rpc/{controller}/{action}",
defaults: new { action = "Get" }
);
// Default route
routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
It will work fine. First the request will be mapped against the RPC, then against the controller (thaty may have or not an Id).
We can also create custom action selector for Api Controllers as follows, so that that can freely work with complex types with traditional "GET,POST,PUT,DELETE":
class ApiActionSelector : IHttpActionSelector
{
private readonly IHttpActionSelector defaultSelector;
public ApiActionSelector(IHttpActionSelector defaultSelector)
{
this.defaultSelector = defaultSelector;
}
public ILookup<string, HttpActionDescriptor> GetActionMapping(HttpControllerDescriptor controllerDescriptor)
{
return defaultSelector.GetActionMapping(controllerDescriptor);
}
public HttpActionDescriptor SelectAction(HttpControllerContext controllerContext)
{
// Get HttpMethod from current context
HttpMethod httpMethod = controllerContext.Request.Method;
// Set route values for API
controllerContext.RouteData.Values.Add("action", httpMethod.Method);
// Invoke Action
return defaultSelector.SelectAction(controllerContext);
}
}
And we can register the same in WebApiConfig as :
config.Services.Replace(typeof(IHttpActionSelector), new
ApiActionSelector(config.Services.GetActionSelector()));
May help users who are running this kind of issue.

Single controller with multiple GET methods in ASP.NET Web API

In Web API I had a class of similar structure:
public class SomeController : ApiController
{
[WebGet(UriTemplate = "{itemSource}/Items")]
public SomeValue GetItems(CustomParam parameter) { ... }
[WebGet(UriTemplate = "{itemSource}/Items/{parent}")]
public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
Since we could map individual methods, it was very simple to get the right request at the right place. For similar class which had only a single GET method but also had an Object parameter, I successfully used IActionValueBinder. However, in the case described above I get the following error:
Multiple actions were found that match the request:
SomeValue GetItems(CustomParam parameter) on type SomeType
SomeValue GetChildItems(CustomParam parameter, SomeObject parent) on type SomeType
I am trying to approach this problem by overriding the ExecuteAsync method of ApiController but with no luck so far. Any advice on this issue?
Edit: I forgot to mention that now I am trying to move this code on ASP.NET Web API which has a different approach to routing. The question is, how do I make the code work on ASP.NET Web API?
This is the best way I have found to support extra GET methods and support the normal REST methods as well. Add the following routes to your WebApiConfig:
routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = #"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new {action = "Post"}, new {httpMethod = new HttpMethodConstraint(HttpMethod.Post)});
I verified this solution with the test class below. I was able to successfully hit each method in my controller below:
public class TestController : ApiController
{
public string Get()
{
return string.Empty;
}
public string Get(int id)
{
return string.Empty;
}
public string GetAll()
{
return string.Empty;
}
public void Post([FromBody]string value)
{
}
public void Put(int id, [FromBody]string value)
{
}
public void Delete(int id)
{
}
}
I verified that it supports the following requests:
GET /Test
GET /Test/1
GET /Test/GetAll
POST /Test
PUT /Test/1
DELETE /Test/1
Note That if your extra GET actions do not begin with 'Get' you may want to add an HttpGet attribute to the method.
Go from this:
config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
To this:
config.Routes.MapHttpRoute("API Default", "api/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
Hence, you can now specify which action (method) you want to send your HTTP request to.
posting to "http://localhost:8383/api/Command/PostCreateUser" invokes:
public bool PostCreateUser(CreateUserCommand command)
{
//* ... *//
return true;
}
and posting to "http://localhost:8383/api/Command/PostMakeBooking" invokes:
public bool PostMakeBooking(MakeBookingCommand command)
{
//* ... *//
return true;
}
I tried this in a self hosted WEB API service application and it works like a charm :)
I find attributes to be cleaner to use than manually adding them via code. Here is a simple example.
[RoutePrefix("api/example")]
public class ExampleController : ApiController
{
[HttpGet]
[Route("get1/{param1}")] // /api/example/get1/1?param2=4
public IHttpActionResult Get(int param1, int param2)
{
Object example = null;
return Ok(example);
}
}
You also need this in your webapiconfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Some Good Links
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
This one explains routing better.
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
In VS 2019, this works with ease:
[Route("api/[controller]/[action]")] //above the controller class
And in the code:
[HttpGet]
[ActionName("GetSample1")]
public Ilist<Sample1> GetSample1()
{
return getSample1();
}
[HttpGet]
[ActionName("GetSample2")]
public Ilist<Sample2> GetSample2()
{
return getSample2();
}
[HttpGet]
[ActionName("GetSample3")]
public Ilist<Sample3> GetSample3()
{
return getSample3();
}
[HttpGet]
[ActionName("GetSample4")]
public Ilist<Sample4> GetSample4()
{
return getSample4();
}
You can have multiple gets like above mentioned.
You need to define further routes in global.asax.cs like this:
routes.MapHttpRoute(
name: "Api with action",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
With the newer Web Api 2 it has become easier to have multiple get methods.
If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute
For example -
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
// GET api/values/7
[Route("{id:int}")]
public string Get(int id)
{
return $"You entered an int - {id}";
}
// GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
[Route("{id:Guid}")]
public string Get(Guid id)
{
return $"You entered a GUID - {id}";
}
}
For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/
Another options is to give the GET methods different routes.
[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
public string Get()
{
return "simple get";
}
[Route("geta")]
public string GetA()
{
return "A";
}
[Route("getb")]
public string GetB()
{
return "B";
}
}
See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/
In ASP.NET Core 2.0 you can add Route attribute to the controller:
[Route("api/[controller]/[action]")]
public class SomeController : Controller
{
public SomeValue GetItems(CustomParam parameter) { ... }
public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
The lazy/hurry alternative (Dotnet Core 2.2):
[HttpGet("method1-{item}")]
public string Method1(var item) {
return "hello" + item;}
[HttpGet("method2-{item}")]
public string Method2(var item) {
return "world" + item;}
Calling them :
localhost:5000/api/controllername/method1-42
"hello42"
localhost:5000/api/controllername/method2-99
"world99"
I was trying to use Web Api 2 attribute routing to allow for multiple Get methods, and I had incorporated the helpful suggestions from previous answers, but in the Controller I had only decorated the "special" method (example):
[Route( "special/{id}" )]
public IHttpActionResult GetSomethingSpecial( string id ) {
...without also also placing a [RoutePrefix] at the top of the Controller:
[RoutePrefix("api/values")]
public class ValuesController : ApiController
I was getting errors stating that no Route was found matching the submitted URI. Once I had both the [Route] decorating the method as well as [RoutePrefix] decorating the Controller as a whole, it worked.
By default [Route("api/[controller]") will generated by .Net Core/Asp.Net Web API.You need to modify little bit,just add [Action] like [Route("api/[controller]/[action]")].
I have mentioned a dummy solution:
// Default generated controller
//
[Route("api/[controller]")
public class myApiController : Controller
{
[HttpGet]
public string GetInfo()
{
return "Information";
}
}
//
//A little change would do the magic
//
[Route("api/[controller]/[action]")]
public class ServicesController : Controller
{
[HttpGet]
[ActionName("Get01")]
public string Get01()
{
return "GET 1";
}
[HttpGet]
[ActionName("Get02")]
public string Get02()
{
return "Get 2";
}
[HttpPost]
[ActionName("Post01")]
public HttpResponseMessage Post01(MyCustomModel01 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
[HttpPost]
[ActionName("Post02")]
public HttpResponseMessage Post02(MyCustomModel02 model)
{
if (!ModelState.IsValid)
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
//.. DO Something ..
return Request.CreateResonse(HttpStatusCode.OK, "Optional Message");
}
}
I am not sure if u have found the answer, but I did this and it works
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET /api/values/5
public string Get(int id)
{
return "value";
}
// GET /api/values/5
[HttpGet]
public string GetByFamily()
{
return "Family value";
}
Now in global.asx
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi2",
routeTemplate: "api/{controller}/{action}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Have you tried switching over to WebInvokeAttribute and setting the Method to "GET"?
I believe I had a similar problem and switched to explicitly telling which Method (GET/PUT/POST/DELETE) is expected on most, if not all, my methods.
public class SomeController : ApiController
{
[WebInvoke(UriTemplate = "{itemSource}/Items"), Method="GET"]
public SomeValue GetItems(CustomParam parameter) { ... }
[WebInvoke(UriTemplate = "{itemSource}/Items/{parent}", Method = "GET")]
public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
The WebGet should handle it but I've seen it have some issues with multiple Get much less multiple Get of the same return type.
[Edit: none of this is valid with the sunset of WCF WebAPI and the migration to ASP.Net WebAPI on the MVC stack]
**Add Route function to direct the routine what you want**
public class SomeController : ApiController
{
[HttpGet()]
[Route("GetItems")]
public SomeValue GetItems(CustomParam parameter) { ... }
[HttpGet()]
[Route("GetChildItems")]
public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
}
Specifying the base path in the [Route] attribute and then adding to the base path in the [HttpGet] worked for me. You can try:
[Route("api/TestApi")] //this will be the base path
public class TestController : ApiController
{
[HttpGet] //example call: 'api/TestApi'
public string Get()
{
return string.Empty;
}
[HttpGet("{id}")] //example call: 'api/TestApi/4'
public string GetById(int id) //method name won't matter
{
return string.Empty;
}
//....
Took me a while to figure since I didn't want to use [Route] multiple times.
None of the above examples worked for my personal needs. The below is what I ended up doing.
public class ContainsConstraint : IHttpRouteConstraint
{
public string[] array { get; set; }
public bool match { get; set; }
/// <summary>
/// Check if param contains any of values listed in array.
/// </summary>
/// <param name="param">The param to test.</param>
/// <param name="array">The items to compare against.</param>
/// <param name="match">Whether we are matching or NOT matching.</param>
public ContainsConstraint(string[] array, bool match)
{
this.array = array;
this.match = match;
}
public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
{
if (values == null) // shouldn't ever hit this.
return true;
if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
return true;
if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
values[parameterName] = request.Method.ToString();
bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.
if (contains == match) // checking if we want it to match or we don't want it to match
return true;
return false;
}
To use the above in your route use:
config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });
What happens is the constraint kind of fakes in the method so that this route will only match the default GET, POST, PUT and DELETE methods. The "true" there says we want to check for a match of the items in array. If it were false you'd be saying exclude those in the strYou can then use routes above this default method like:
config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });
In the above it is essentially looking for the following URL => http://www.domain.com/Account/Status/Active or something like that.
Beyond the above I'm not sure I'd get too crazy. At the end of the day it should be per resource. But I do see a need to map friendly urls for various reasons. I'm feeling pretty certain as Web Api evolves there will be some sort of provision. If time I'll build a more permanent solution and post.
Couldn't make any of the above routing solutions work -- some of the syntax seems to have changed and I'm still new to MVC -- in a pinch though I put together this really awful (and simple) hack which will get me by for now -- note, this replaces the "public MyObject GetMyObjects(long id)" method -- we change "id"'s type to a string, and change the return type to object.
// GET api/MyObjects/5
// GET api/MyObjects/function
public object GetMyObjects(string id)
{
id = (id ?? "").Trim();
// Check to see if "id" is equal to a "command" we support
// and return alternate data.
if (string.Equals(id, "count", StringComparison.OrdinalIgnoreCase))
{
return db.MyObjects.LongCount();
}
// We now return you back to your regularly scheduled
// web service handler (more or less)
var myObject = db.MyObjects.Find(long.Parse(id));
if (myObject == null)
{
throw new HttpResponseException
(
Request.CreateResponse(HttpStatusCode.NotFound)
);
}
return myObject;
}
If you have multiple Action within same file then pass the same argument e.g. Id to all Action. This is because action only can identify Id, So instead of giving any name to argument only declare Id like this.
[httpget]
[ActionName("firstAction")] firstAction(string Id)
{.....
.....
}
[httpget]
[ActionName("secondAction")] secondAction(Int Id)
{.....
.....
}
//Now go to webroute.config file under App-start folder and add following
routes.MapHttpRoute(
name: "firstAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapHttpRoute(
name: "secondAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Simple Alternative
Just use a query string.
Routing
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Controller
public class TestController : ApiController
{
public IEnumerable<SomeViewModel> Get()
{
}
public SomeViewModel GetById(int objectId)
{
}
}
Requests
GET /Test
GET /Test?objectId=1
Note
Keep in mind that the query string param should not be "id" or whatever the parameter is in the configured route.
The concept of multiple methods in a single asp.net web api controller makes it easier to have more than 1 method in code.
I was able to implement following the steps in the above solutions and came up with this final code
In the WebApiConfig.cs ,set up the following Route config, in this order
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.Routes.MapHttpRoute(
name: "DefaultApiAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.MapHttpAttributeRoutes();
}
}
Then in your controller reference the [HttpGet] for GET or [HttpPost] for POST with [ActionName] see sample code below
namespace WebRESTApi.Controllers
{
//[RoutePrefix("api/Test")]
public class TestController : ApiController
{
[HttpGet]
[ActionName("AllEmailWithDisplayname")]
public string AllEmailWithDisplayname()
{
return "values";
}
[HttpPost]
[ActionName("Authenticate")]
// POST: api/Authenticate
public object Authenticate([FromBody()] object Loginvalues)
{
return true;
}
[HttpPost]
[ActionName("ShowCredential")]
// POST: api/Showcredential
public object Showcredential([FromBody()] object Loginvalues)
{
return "Username: "
}
}
}
you can then consume the different methods via client or postman using the format
http://url/api/controller/actionname
Modify the WebApiConfig and add at the end another Routes.MapHttpRoute like this:
config.Routes.MapHttpRoute(
name: "ServiceApi",
routeTemplate: "api/Service/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Then create a controller like this:
public class ServiceController : ApiController
{
[HttpGet]
public string Get(int id)
{
return "object of id id";
}
[HttpGet]
public IQueryable<DropDownModel> DropDowEmpresa()
{
return db.Empresa.Where(x => x.Activo == true).Select(y =>
new DropDownModel
{
Id = y.Id,
Value = y.Nombre,
});
}
[HttpGet]
public IQueryable<DropDownModel> DropDowTipoContacto()
{
return db.TipoContacto.Select(y =>
new DropDownModel
{
Id = y.Id,
Value = y.Nombre,
});
}
[HttpGet]
public string FindProductsByName()
{
return "FindProductsByName";
}
}
This is how I solved it. I hope it will help someone.

Categories

Resources