asp.net web api attribute routing - c#

API
[RoutePrefix("api/diagnostics")]
public class DiagnosticsController : ApiController
{
[HttpPost]
[Route("pings")]
public IHttpActionResult Pings(Ping ping)
{
}
}
Ping
public class Ping
{
public Guid ServerKey {get;set;}
public DateTime CreatedDateTime {get;set;}
}
I am trying to test the class using Postman application. Here is the Screenshot.
The message I get back is:
{
"message": "No HTTP resource was found that matches the request URI 'http://localhost:61668/api/diagnostics/pings'.",
"messageDetail": "No action was found on the controller 'Diagnostics' that matches the request."
}
I am failing to understand why it does not match the post action in Diagnostics controller. The only other route configured is the default route:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{key}",
defaults: new { key = RouteParameter.Optional }
);
Also attribute routing is enabled: config.MapHttpAttributeRoutes();

Try to mark your parameter with [FromBody] attribute - public IHttpActionResult Pings([FromBody] Ping ping).

Related

ASP.NET Web API - The requested resource does not support http method 'GET'

I am make POST call into my Web API using Postman. I get the error: "The requested resource does not support http method 'GET'."
I am not making a GET call. If I do call one of my GET methods, it works fine and returns the expected result.
My controller class:
[RoutePrefix("api/login")]
public class LoginController : ApiController
{
ModelContext db = new ModelContext();
[HttpPost]
[Route("validate")]
public HttpResponseMessage Validate([FromBody] LoginViewModel login)
{
try
{
var message = Request.CreateResponse(HttpStatusCode.OK);
return message;
}
catch (Exception ex)
{
var message = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
return message;
}
}
}
I have the Web API running locally and call with this URL:
http://localhost:44303/api/login/validate
This url returns:
<Error>
<Message>
The requested resource does not support http method 'GET'.
</Message>
</Error>
My routing in WebApiConfig.cs
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
While this controller message returns HttpResponseMessage, I have tested by changing the response to "string" and just returning a string value, but I get the same error.
I have read through so many SO posts but none appear to fix my issue. I am at a total loss to explain this behavior. I appreciate any ideas.
EDIT
I have tested GETs in other controllers and they are returning data as expected.
EDIT FOR CONTEXT 6/3/2020
This method in the default ValuesController works:
[Route("api/values")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
These 2 methods in the SAME controller do not work:
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
EDIT #2 6/3/2020
Now all of my api methods are working for the default ValuesController. I do not know why.
My custom POST methods in other controllers such as the Post method above are still not working. Here is my current WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "Api_Get",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Get" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
);
config.Routes.MapHttpRoute(
name: "Api_Post",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional, action = "Post" },
constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) }
);
}
I do not have any middleware or special routing that I know of. Any exception handling would be simple try-catch.
I am trying to use attribute routing vs convention but that seems to be an issue.
You don't need to create a route table by HttpMethods because you have [HttpPost] attribute.
Replace all config.Routes.MapHttpRoute by
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
It's preferable to use Attribute Routing for Web API project. It will reduce the chances of errors because in RouteConfig class there can be any mistake while creating a new custom route. Also, you don’t have to take care of the routing flow i.e, from most specific to most general. All here is the attribute you use the action method.

Unable to connect to ASP.NET web api when I add additional parameters

I am trying understand Web Api 2 (MVC project in Visual Studio).
The method is
[HttpPost]
public string Post(int id, string e, bool o)
///code removed
Using Postman, I can query using Post and the path http://localhost:62093/api/Demo/5. This works and returns the expected value.
Now I want to add more parameters and this is where it goes wrong!
I have updated my method to
[HttpPost]
public string Post(int id, string e, bool o)
Now when I attempt to query this using (again) Post and the path http://localhost:62093/api/Demo/5 I see
"Message": "The requested resource does not support http method 'POST'."
I then try to change the URL, so when I use Post and the new path http://localhost:62093/api/Demo/5/a/false I see an HTML file response of
The resource cannot be found
This has been mentioned before on Stackoverflow and from what I've understood is about the URL being 'incorrect'
Thinking this could be an issue with routes I updated mine to
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}/{s}/{o}",
defaults: new { id = RouteParameter.Optional, s = RouteParameter.Optional, o = RouteParameter.Optional }
);
But the same issue persists. I'm not sure what I've done wrong.
This is a routing issue. you have not configured your routes correctly.
First let us update the WebApiConfig.cs file
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 }
);
}
}
Now with that configured I would suggest using Attribute routing
public class DemoController : ApiController {
[HttpPost]
[Route("api/Demo/{id:int}/{e}/{o:bool}")] //Matches POST api/Demo/5/a/false
public IHttpActionResult Post(int id, string e, bool o) {
return Ok();
}
}
I would finally suggest reading up on Attribute Routing in ASP.NET Web API 2 to get a better understanding on how to properly route to your API controllers

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.

attribute [Route] is not working without [RoutePrefix] in ASP.NET WebApi

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 }
);

Categories

Resources