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.
Related
http://localhost:2000/api/{Controller}
I need to create index page.
URI : http://localhost:2000/api
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "api",
routeTemplate: "api"
);
And the api
[RoutePrefix("api")]
public class Api
{
[HttpGet]
public HttpResponseMessage Get()
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(Encoding.ASCII.GetBytes("API"));
return result;
}
}
But when I open http://localhost:2000/api, it's not working.
No HTTP resource was found that matches the request URI http://localhost:2000/api.
Need to make sure you follow the suggested syntax for API controllers.
[RoutePrefix("api")]
public class MyApiController: ApiController {
[HttpGet]
[Route("")] // GET api
public IHttpActionResult Get() {
return Ok("API");
}
}
Which includes having your controller derived from ApiController.
If using attribute routing with route prefix you still need to provide a route on the action.
[Route("")] in this case above will act as the default rout for that controller.
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.
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.
For the last couple of hours i'm trying to execute web api action hosted in asp.net webforms website.
I know its wired but due to old project design i have to do this.each time i call the action in Controller i got
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:3049/api/chart/test?id=58'.","MessageDetail":"No action was found on the controller 'Chart' that matches the request."}
My Project structure as follows:-
My Classes code looks very simple:-
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
My Controller:-
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class ChartController : ApiController
{
[HttpGet]
public static string test(string id)
{
return id;
}
}
What i miss ?
Make your action method non-static. In Microsoft's documentation, they say this:
Which methods on the controller are considered "actions"? When selecting an action, the framework only looks at public instance methods on the controller.
Also, your routing is in the form of api/{controller}/{id} but the URL you're accessing is in the form of /api/controller/action?id=string. Notice the mismatch? You can change your action method to match your route.
[HttpGet]
public string Get(string id)
{
return id;
}
And then access it at /api/chart/58.
With the default routing structure in Web API, your route tells it what controller, the selected action method is based on the HTTP Method (GET, POST, PUT, DELETE, HEAD, OPTIONS, PATCH) and the parameters, and then other segments of the URL become the parameters.
Learn more detail about Web API Routing on MSDN.
Refer to the official ASP.NET attribute routing documentation, it seems that Route attribute can be used without RoutePrefix.
But, in my webapi controller, below cases are happened.
1. Not working. (error: No matched http route found)
public class GroupController : ApiController
{
[Route("api/group/{id}/register")]
public IHttpActionResult Post(int id, InputModel model)
{
return Ok();
}
}
2. Working good.
[RoutePrefix("api/group")]
public class GroupController : ApiController
{
[Route("{id}/register")]
public IHttpActionResult Post(int id, InputModel model)
{
return Ok();
}
}
Is it right that Route attribute should be used with RoutePrefix, or what am I missing?
In addition, below code is my WebApi route config in WebApiConfig.Register class.
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{subId}",
defaults: new { id = RouteParameter.Optional, subId = RouteParameter.Optional }
);