Unable to call WebApi 2 method - asp.net-web-api2

I've added a webapi 2 controller to my project, inside api > LoginAPi as shown here:
Inside LoginApi I have the following:
[RoutePrefix("api/LoginApi")]
public class LoginApi : ApiController
{
// GET api/<controller>/5
public string Get(int id)
{
return "value";
}
}
Inside my global.asax file I have:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
Inside App_Start I have the following:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I then put a break point inside the Get method within LoginAPI and run the project and type the following into the URL:
http://localhost:37495/api/LoginApi/4
But I get :
No HTTP resource was found that matches the request URI 'http://localhost:37495/api/LoginApi/4'.
So I thought OK let me specify the method name as so
http://localhost:37495/api/LoginApi/Get/4
This returns:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Now I've been looking at this for a while so maybe I've missed something obvious, but if someone can please tell me what I'm doing wrong I'd very much appreciate it.

The routeTemplate you have set up would work for convention-based routing except for the fact that Web API adds the string "Controller" when searching for the controller class (as per this article). You therefore need to rename your controller class LoginApiController in order for the convention-based routing to work.
For attribute-based routing, the addition of the RoutePrefix attribute should be combined with a Route attribute on your action. Try adding the following to your Get method in your controller:
[HttpGet]
[Route("{id}")]
And then navigate to http://localhost:37495/api/LoginApi/4.

Related

Configurable route prefix for controller

I'm using ASP.NET Core 6 and trying to have the base path of my API controller be configurable (so that users can choose the base path themselves to avoid conflicts with other controllers).
I tried setting up the following route:
string configurablePrefix = "/temp";
endpoint.MapControllerRoute(
name: "MyRouteName",
pattern: configurablePrefix + "/{action=MyDefaultAction},
defaults: new { controller = "MyController" });
Where MyController is defined like this:
[ApiController]
public class MyController : ControllerBase
{
[HttpGet("MyDefaultAction")]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
This causes no errors during startup, but when I access `https://localhost/temp/MyDefaultAction I get a 404
How can I get this to work so that actions in MyController are accessible on whatever start path the user chooses (i.e. change it to respond to /othertemp/MyDefaultAction instead)?
From your code, you are using ApiController, which cannot be routed by setting the corresponding route in Startup.cs or Program.cs.
ApiController must have attribute routing, and attribute routing has a higher priority than conventional routing, so it will override the conventional routing you defined.
You can choose to use attribute routing to define the controller name as temp, so that the corresponding endpoint can be matched in ApiController:
[Route("temp")]
[ApiController]
public class MyController : ControllerBase
{
[HttpGet("MyDefaultAction")]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
Test Result:
Or use an MVC controller:
public class MyController : Controller
{
[HttpGet]
public IActionResult MyDefaultAction()
{
return new JsonResult("Hello");
}
}
Routing:
string configurablePrefix = "/temp";
endpoint.MapControllerRoute(
name: "MyRouteName",
pattern: configurablePrefix + "/{action}",
defaults: new { controller = "My", action = "MyDefaultAction" });
Test Result:
reference link: Create web APIs with ASP.NET Core.

Why does not working version in asp.net core controller

I want to use api version in my .net core project.Then search web and find that's solution.
Even though do exactly all solutions,but I can't get desired result.
So if any can help me,Please show me..
I add Microsoft.AspNetCore.Mvc.Versioning 4.0.0 Package in my project and ..
StartUp.cs
Then in my Controller Add Rout Attribute as Shown :
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
private readonly IBus _client;
private readonly string AppBaseUrl = MyHttpContext.AppBaseUrl;
//private readonly IGetUrl _globalUrl;
public SellerController(IBus client/*, IGetUrl globalUrl*/)
{
_client = client;
//_globalUrl = globalUrl;
}
[HttpGet("/Sellers/{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
...
}
}
With these code I expected that I can send request to 'Info' method by this url :
But that's not working and get 404 error code status.. when I delete "/v1.0" from url and send request, that's working. I will be glad to help me .. Thanks
In your code, we can find that you applied [HttpGet("/Sellers/{SellerId}")] with route
template begin with / to Info action method, which don't get combined with route templates applied to the controller. To make request to 'Info' method, you could use below URL.
https://localhost:5090/sellers/17
I expected that I can send request to 'Info' method by this url : https://localhost:5090/v1.0/sellers/17
To achieve your requirement, you can try to modify the code like below.
[HttpGet("/v{version:apiVersion}/Sellers/{SellerId}")]
public async Task<IActionResult> Info(long SellerId)
{
//...
//for testing purpose
return Ok(SellerId);
}
Test Result
Update:
If you'd like to include v{version:apiVersion} in route template of controller level attribute routing, you can try to apply [HttpGet("{SellerId}")] to Info action method and make request with https://localhost:5090/v1.0/seller/17.
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
[HttpGet("{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
//...

Web API One action works while a nearly identical one doesn't?

Error Message
{
"Message": "No HTTP resource was found that matches the request URI 'https://localhost:44390/api/UserRoutes?effectiveDate=3/29/2019'.",
"MessageDetail": "No type was found that matches the controller named 'UserRoutes'."
}
Working Action
public class AdvanceOrderApiController : BaseApiController
{
[HttpGet, Route("api/AdvanceOrders")]
public AdvanceOrdersResult GetAdvanceOrdersForRouteDate(string route, DateTime effectiveDate)
{
...
}
}
// JavaScript Usage: route="0100" and effectiveDate="03/29/2019".
API.SendRequest("/api/AdvanceOrders", "GET", { route: route, effectiveDate: effectiveDate }, success, failure);
Not Working Action
public class UserApiController : BaseApiController
{
[HttpGet, Route("api/UserRoutes")]
public IEnumerable<string> GetUserRoutes(DateTime effectiveDate)
{
...
}
}
// JavaScript Usage: effectiveDate="03/29/2019"
API.SendRequest("/api/UserRoutes", "GET", { effectiveDate: effectiveDate }, success, failure);
WebApiConfig
Not sure that it's relevant since I'm just declaring the route for each action, but...
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
...
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
API.SendRequest
This function is just a wrapper around jQuery's $.ajax function, nothing fancy. If the code is necessary I'll present it, but it works for all my other API calls so I can't imagine it would be the source of the problem.
These actions are nearly identical, why does one work and the other doesn't?
Passing the date in as Igor said in the comments presented an error message that revealed that I had an Api controller in my Permissions area that had a route also named api/UserRoutes.
Once I changed the name of the route the problem resolved.
I just wish it could have just told me this error message from the start.

Can I create more function in ApiController?

I am new in web api and I am creating a demo with default Web API, I see that ValuesController has default 4 functions Get,Post,Put and Delete. I see that the ValuesController impleament 4 function to ApiController which can not modify. So, Can I write some more functions like search item by price or model ? If can, what url on browser to run debug for new function ?
thankyou
It sounds like you need to add new actions to your controller. You will need to modify (or add to) your Routes in your WebApiConfig.cs file to include action mapping.
For example, let's say you update your Controller with the additional functions GetTestString1 and GetTestString2:
public class TestController : ApiController
{
public String GetTestString1(int id)
{
return "Test String 1 for " + id;
}
public String GetTestString2(int id)
{
return "Test String 2 for " + id;
}
}
To perform the routing to these new functions you need to add the following to the WebApiConfig.cs file in the App_Start folder:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// This mapping entry may already exist for you. Leave it alone
// so your existing default functions continue to work properly.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Add this to route your new functions:
config.Routes.MapHttpRoute(
name: "TestStringApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The above routeTemplate "api/{controller}/{action}/{id}" is how the request URL will be routed to your controller and actions (functions). The {controller} part of the URL will route to your TestController class. The {action} part of the URL is the additional function you asked about and will be mapped to GetTestString1 or GetTestString2 depending on what you request in your URL.
When you open your browser to this address,
http://localhost:60303/api/Test/GetTestString1/100
the route you registered in the WebApiConfig.cs will map the url to your Testcontroller's GetTestString1 action (function) with 100 as the input parameter and will return "Test String 1 for 100" to the browser.
You can call your Testcontroller's GetTestString2 action (function) like this
http://localhost:60303/api/Test/GetTestString2/101
and "Test String 2 for 101" will be returned to the browser.
You can learn more about the how the default functions work (get, post delete) and more about actions and parameters here:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
Here are some related discussions similar to this topic:
Routing with Multiple Parameters using ASP.NET MVC
Routing with action after id parameter in Web API

404 trying to use web api endpoint

I'm trying to add a web api controller to my MVC project. It's an MVC 3 project that I've upgraded to MVC4. I'm trying to get the "test" simple api controller to work, and currently getting a 404. Here's what I've done:
I've added all the required packages.
I've added my webapi config to my Global Application_Start():
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration); // Web API
This then calls my static Register method:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I have a ApiController defined in my web app:
public class SitechangesController : ApiController
{
/// GET api/default1
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
And finally, when I build it all and browse to my site on localhost http://localhost/api/Sitechanges , I get a 404.
If I do a file/new project and create a web api project from scratch, I don't have these problems. Can anyone help?
Thanks
Matt
It seems adding the web api config before the "normal" routes fixes it!
WebApiConfig.Register(GlobalConfiguration.Configuration); // Moved to the top
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
Your controller must end in ...Controller.cs.
For example:
Test.cs and TestControllerV2.cs will return 404.
TestController.cs and TestV2Controller.cs will return 200.
I see yours does, but I came across your post when searching for why a 404 was returned.