ASP.NET web API not showing actions - c#

I have an ASP.NET web api that was created with Entity framework.I added my controller in the controller's folder and it generated the API code for me.but when i run the application it does not show the controller that i added,it only shows the default API page that comes with the application like below.
This is what it displays
I would like it to look like this
Expected Output

public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
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 }
);
}
}
NOTE: Add 'ActionApi' route in WebApiConfig.cs file

Related

Web API route not getting called

This is my web API config:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ReaderTags",
routeTemplate: "Reader/{readerID}/Tags"
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
I want that when I call my URL /Reader/abc/Tags it should call my ReaderController's Tags action and pass abc as the string parameter.
But somehow it is using the DefaultAPI's route and trying to find abc as an action in ReaderController.
What am I missing?
The route mapping is missing defaults that would let the route table know what controller and action to invoke for routes matching the template
config.Routes.MapHttpRoute(
name: "ReaderTags",
routeTemplate: "Reader/{readerID}/Tags",
defaults: new { controller = "Reader", action = "Tags" }
);
The route template also assumes that the string parameter on the action shares the same name: i.e: readerID.
public IHttpActionResult Tags(string readerID) {
//...
}
And since config.MapHttpAttributeRoutes(); is also configured, then the same can be achieved via attribute routing instead of convention-based routing like this
//GET Reader/abc/Tags
[HttpGet]
[Route("Reader/{readerID}/Tags")]
public IHttpActionResult Tags(string readerID) {
//...
}

WebApi2 can not find route

[RoutePrefix("subscriptions")]
public class SubscriptionsController : ApiController
{
private SubscriptionsService _subscriptionsService;
public SubscriptionsController()
{
_subscriptionsService = new SubscriptionsService();
}
[Route("{email}")]
[HttpGet]
public IHttpActionResult Get(string email)
{
but when I try
http://localhost:51561/api/subscriptions/myEmail
No HTTP resource was found that matches the request URI
'http://localhost:51561/api/subscriptions/myEmail'.
any idea why?
I also set everything in WebApiCOnfig
public static class WebApiConfig
{
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 }
);
}
}
You have tried a wrong URL.
Correct URL should be,
http://localhost:51561/subscriptions/myEmail
OR
If you need API prefix, then you need to change the route prefix of the controller as below,
[RoutePrefix("API/subscriptions")]
then this URL will work,
http://localhost:51561/api/subscriptions/myEmail
Note that , here you are using two routing, default routing and attribute routing. if you need to continue with attribute routing , you can comment out the default routing.
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
I Suppose you are creating some webApi service ? Did you register this route in global.asax.cs ? Something like this :
httpConfiguration.Routes.MapHttpRoute(
name: "MyWebApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { controller = "ControllerName", action = "ActionName", id = RouteParameter.Optional },
constraints: null
);

Web Api - response in JSON format - swagger documentation

I want create ASP.NET WEB API with swagger documentation, but I have strange problem. When I set api format using my own implemenation of JSON formatter, swagger documenation is disabled. In console I can see that JavaScript Exception is throwing.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
{"swagger":"2.0","info":{"version":"v1","title":"REST","description":null,"termsOfService":null,"contact":null,"license":null,"vendorExtensions":{}},"host":"localhost:58144","basePath":null,"schemes":["http"],"consumes":null,"produces":null,"paths":{"/api/Users":{"$ref":null,"get":{"tags":["Users"],"summary":null,"description":null,"externalDocs":null,"operationId":"Users_GetUsers","consumes":[],"produces":["application/json","text/json","application/xml","text/xml"],"parameters":null,"responses":{"200":{"description":"OK","schema":{"$ref":null,"format":null,"title":null,"description":null,"default":null,"multipleOf":null,"maximum":null,"exclusiveMaximum":null,"minimum":null,"exclusiveMinimum":null,"maxLength":null,"minLength":null,"pattern":null,"maxItems":null,"minItems":null,"uniqueItems":null,"maxProperties":null,"minProperties":null,"required":null,"enum":null,"type":"array","items":

Need To use Identical Controllers in Web API 2

How can i use two identical Controllers in Web API 2.
I need to use URL as follows.
mysite/api/Contacts/get/2
and
mysite/api/v1/Contacts/get/2
but if i use seperate folder for this it gives an error.
my WebApiConfig.cs like this
public static class WebApiConfig
{
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 }
);
config.Routes.MapHttpRoute(
name: "DefaultApi2",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
This is the Error
Multiple types were found that match the controller named 'default'.
This can happen if the route that services this request
('api/v1/{controller}/{id}') found multiple controllers defined with
the same name but differing namespaces, which is not supported. The
request for 'default' has found the following matching controllers:
TestWebAPI.Controllers.DefaultController
TestWebAPI.Controllers.v1.DefaultController
How Can i Achieve this?... Basically I need this for Versioning.
This can happen if the route that services this request ('api/v1/{controller}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported.
This means that you have two distinct controllers named DefaultController (as you mentioned).
If you want to serve both urls with the same controller, just delete the one in v1 folder. If you want to serve each url with each controller you should specify the namespace for each one.
var r = routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
r.DataTokens["Namespaces"] = new string[] {"Foo"};
More info in this blog post.

IIS 7.5 only shows homecontroller

I have my IIS set up like this:
The default website works like it should.
But the API only loads the default page
all the other routes give me
Any clue on how to fix this?
this is the WebApiConfig.cs from the api
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.Filters.Add(new AuthorizeAttribute());
}
Found the sollution:
The problem was that the /api worked as root, so /api/api/videos would call the video controller.

Categories