Web API call not reaching? - c#

i am using route prefix in my api
[RoutePrefix("api/currencies")]
public class DefCurrencyController : ApiController
{
[HttpGet, Route("")]
public List<DefCurrency> GetAllCurrencies()
{
return DefCurrency.AllDefCurrency;
}
}
my webapi config file
namespace ERPServices
{
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 }
//);
}
}
}
i am trying to reach or acess the GetAllCurrencies() using
http://localhost:1865/api/currencies
it returns error
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
what should i do to test my controller api ?

Ditch the RoutePrefix attribute on the controller and just declare the route you want on the method:
public class DefCurrencyController : ApiController
{
[HttpGet, Route("api/currencies")]
public List<DefCurrency> GetAllCurrencies()
{
return DefCurrency.AllDefCurrency;
}
}
Route prefix is for where you want to declare a portion of the route to apply to all methods in the controller (e.g. they are in an area).
Also, you don't need HttpPost here, this should be GET only.
You should also check that in your WebApiConfig you are calling config.MapHttpAttributeRoutes(); before any convention based routing.

Please try below of test the API
http://localhost:1865/api/currencies/GetAllCurrencies

There are several things required to make WebAPI work.
Add this is you project:
using System.Web.Http;
namespace WebConfig
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
}
}
}
And in your Global.asax file, add this in the Application_Start to call the Register method:
GlobalConfiguration.Configure(WebApiConfig.Register);
Also, in the web service, try changing for the following values to test the routing:
[RoutePrefix("api")]
public class DefCurrencyController : ApiController
{
[Route("currencies")]
public HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
}

Related

Web API Routing Not Recognising Parameters

I have the following WebAPI controller:
namespace MyApp.WebApi.Controllers
{
[RoutePrefix("api/listing")]
public class ListingController : ApiController
{
[Route("{firstparam:int?}/{nextparam:int?}")]
public IEnumerable<ListItem> Get(int firstparam = 100, int nextparam = 12)
{
// firstparam is always 100, and nextparam is always 12
However, I've tried specifying the URL:
http://localhost:56004/#/listing?firstparam=2
If I specify the URL like this:
http://localhost:56004/#/listing/2
Then it breaks the routing.
Clearly I'm missing something regarding routing; please could someone point me in the right direction?
You are using multiple optional parameter which don't work well for routeTemplates. Normally the last parameter tends to be the optional parameter.
Documentation: Attribute Routing in ASP.NET Web API 2: Optional URI Parameters and Default Values
FIrst make sure the attribute routing is enabled
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
To get what you are after
[RoutePrefix("api/listing")]
public class ListingController : ApiController {
//GET api/listing
//GET api/listing?firstparam=x
//GET api/listing?nextparam=y
//GET api/listing?firstparam=x&nextparam=y
[HttpGet]
[Route("")]
public IEnumerable<ListItem> Get(int firstparam = 100, int nextparam = 12) { ... }
}
The problem with having multiple inline parameters that are optional is that the router wont know which to use which is why they tend to be at the end of the url.
However to get them inline like how you mentioned in your example you are going to need multiple routes.
[RoutePrefix("api/listing")]
public class ListingController : ApiController {
//GET api/listing
[HttpGet]
[Route("")]
public IEnumerable<ListItem> Get() { return Get(100, 12); }
//GET api/listing/2
//GET api/listing/2/5
[HttpGet]
[Route("{firstparam:int}/{nextparam:int?}")]
public IEnumerable<ListItem> Get(int firstparam, int nextparam = 12) { ... }
}
You could try using [FromUri] attribute within the params of the Get() method to extract any query params being passed into the "/listing" uri along with a class that consists of int properties firstparam and secondparam.
namespace MyApp.WebApi.Controllers
{
[RoutePrefix("api/listing")]
public class ListingController : ApiController
{
[Route("")]
[HttpGet]
public IEnumerable<ListItem> Get([FromUri] ClassRepresentingParams params)
{
Hopefully that helps.

WebAPI no HTTP resource found

So i have setup an ASP.NET WebAPI app and whenever i try to call the API i get this message:
<Error>
<Message>
No HTTP resource was found that matches the request URI
'http://localhost:62834/api/PiDBTest'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'PiDBTest'.
</MessageDetail>
</Error>
I have tried a few different urls to get to call the API but still cant get anywhere with it.
I have been using the following url to call the API
http://localhost:62834/api/PiDBTest
Can't seem to see why I'm not getting any success from the call?
Below is the code for the API controller and the RouteConfig
PiDBTest:
public class PiDBTest : ApiController
{
private pidbEntities db = new pidbEntities();
// GET: api/PiDBTest
public IQueryable<PiData> GetPiDatas()
{
return db.PiDatas;
}
}
RouteConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
With attribute routing enabled, this will work.
[RoutePrefix("api/PiDBTest")]
public class PiDBTest : ApiController
{
private pidbEntities db = new pidbEntities();
// GET: api/PiDBTest
[HttpGet]
[Route("")]
public IQueryable<PiData> GetPiDatas()
{
return db.PiDatas;
}
}
Please try change your API class as follows,
public class PiDBTestController : ApiController
{
private pidbEntities db = new pidbEntities();
// GET: api/PiDBTest
[HttpGet]
[Route("")]
public IQueryable<PiData> GetPiDatas()
{
return db.PiDatas;
}
}
Could you add [HttpGet] on top of your Method
public IQueryable GetPiDatas()
In my case, the controller class name didn't include the word "Controller" in it. I changed the class name from "Vendor" to "VendorController" then it started working.

404 when passing web api parameters

I'm trying to get this method to work:
public class DocumentenController : ApiController
{
[HttpPost]
[Route("DeleteDocument/{name}/{planId}")]
public IHttpActionResult DeleteDocument(string name, int planId)
{
_documentenProvider.DeleteDocument(planId, name);
return Ok();
}
}
This is the WebApiConfig :
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: UrlPrefix + "/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional}
);
But I get a 404 when I call it like this using a post:
http://localhost/QS-documenten/api/documenten/deletedocument/testing/10600349
What is the proper way do solve this?
The URL in example does not match attribute route on controller.
To get
http://localhost/QS-documenten/api/documenten/deletedocument/testing/10600349
to work, assuming that http://localhost/QS-documenten is the host and root folder, and that api/documenten is the api prefix then add a route prefix to the controller...
[RoutePrefix("api/Documenten")]
public class DocumentenController : ApiController {
//eg POST api/documenten/deletedocument/testing/10600349
[HttpPost]
[Route("DeleteDocument/{name}/{planId}")]
public IHttpActionResult DeleteDocument(string name, int planId) {
_documentenProvider.DeleteDocument(planId, name);
return Ok();
}
}
Source: Attribute Routing in ASP.NET Web API 2 : Route Prefixes
You must send your request as follows:
http://localhost/QS-documenten/deletedocument/testing/10600349
When you use route attribute, the custom route override default api routing configuration.

Unable to get multiple literal routings to work in the same controller - Web Api 2

I'm using attribute routing and am having this controller with two Get-methods.
When requesting any of these two Get methods I get 404 back and I don't understand why since I've followed this guide from Microsoft (especially this part).
This is how the Controller looks like:
[RoutePrefix("api/rolesubscriptions")]
public class RoleSubscriptionsController : ApiController
{
Route("roles")]
public async Task<IHttpActionResult> GetRoles()
{
}
[Route("tags")]
public async Task<IHttpActionResult> GetTags()
{
}
}
And this is my WebApiConfig.cs file
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Now based on this configuration I think that I would be able to do these requests
/api/rolesubscriptions/roles
and
/api/rolesubscriptions/tags
But both these requests return 404. Any help to help solve my problem is very appreciated.
EDIT 1
This is how my Application_Start() looks like
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
}
The Startup class exists but doesn't have any code that has to do with routing, only authentication.
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
// Authenication code omitted
}

ASP.NET Web API Route Controller Not Found

I am trying to post to the following Web API:
http://localhost:8543/api/login/authenticate
LoginApi (Web API) is defined below:
[RoutePrefix("login")]
public class LoginApi : ApiController
{
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
WebApiConfig.cs:
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 }
);
}
Here is the error I get:
Request URL:http://localhost:8543/api/login/authenticate
Request Method:POST
Status Code:404 Not Found
Remote Address:[::1]:8543
Your controller name "LoginApi" needs to end in "Controller" in order for the framework to find it. For example: "LoginController"
Here is a good article which explains routing in ASP.NET Web API: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
You are using login as your route prefix on your controller so trying to call
http://localhost:8543/api/login/authenticate
will not be found as this code
[RoutePrefix("login")]
public class LoginApi : ApiController
{
//eg:POST login/authenticate.
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
will only work for
http://localhost:8543/login/authenticate
You need to change your route prefix to
[RoutePrefix("api/login")]
public class LoginApi : ApiController
{
//eg:POST api/login/authenticate.
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
Notice you are using both attribute routing on the controller/action and convention routing with config.Routes.MapHttpRoute.
config.Routes.MapHttpRoute will map the routes as per your definition "api/{controller}/{id}".
While attribute routing, will map the routes based on how you've defined them: /login/authenticate.
Also, since you are using both attribute routing and convention routing, attribute routing takes presendence. I would stick to using one or the other. Having both adds a bit of confusion as to what route will be used to access an action method.

Categories

Resources