I am trying to build a microservice web content api which is a simple ASP.NET MVC Web Project.
My Question is, how can I create a main page which is documentation for routes just like swagger for WEB APIs
I have a RouteConfig.cs like below
routes.MapRoute(RouteNames.X,
"X/{action}",
new { controller = "XController", action = "XAction" });
routes.MapRoute(RouteNames.Y,
"Y/{action}",
new { controller = "YController", action = "YAction" });
routes.MapRoute(RouteNames.Z,
"Z/{action}",
new { controller = "ZController", action = "ZAction" });
First...add the WebApiConfig.cs file in App_Start folder and above code use in asp.net mvc not for asp.net mvc webapi. Currently you are mapping the wrong thing. Below I have the sample code & link.
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}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Getting Started with ASP.NET Web API 2 (C#)
Related
i'm using asp.net web api. And my problem is "Multiple actions were found that match the request" but i set route template already and in my controller i have 2 POST action
**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}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
And this is my controller
1. [Route("{InsertRoadMap}")]
[HttpPost]
public mdRoadMapCallBack InsertRoadMap(mdEvent _mdEvent){
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
2. [Route("{UpdateRoadMap}")]
[HttpPost]
public mdRoadMapCallBack UpdateRoadMap(mdEvent _mdEvent)
{
mdRoadMapCallBack _mdRoadMapCallBack = new mdRoadMapCallBack();
return _mdRoadMapCallBack;
}
What is wrong ? Please help. Thank you so much
The Route attribute doesn't seems to be implemented correctly.
Use it like this instead -
[Route("api/mycontroller/InsertRoadMap")]
[Route("api/mycontroller/UpdateRoadMap")]
Now you can browse like this - http://server/api/mycontroller/InsertRoadMap
You can also use RoutePrefix attribute at controller level so that you do not have to repeat api for every method.
[RoutePrefix("api")]
And then you can set routes like -
[Route("mycontroller/InsertRoadMap")]
[Route("mycontroller/UpdateRoadMap")]
See here and here some more information on attribute routing
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
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":
For supportability reasons I'm porting an application from .Net Core with ReactJs to .Net MVC.
This also uses Redux for state handling.
This seemed to be going ok but for some reason the WebAPI calls all fail with 404 errors.
I'm pretty sure the routing is correct as per the failing calls but clearly something is getting lost somewhere.
The default MVC controller that was added as an entry point works fine, it's just the ported WebAPI controllers that seem to fail.
I'm not allowed to post the entire code for commercial reasons but this is what the controller and one of the actions in question looks like:
namespace Api.Controllers
{
/// <summary>
/// Account management.
/// </summary>
[Authorize]
[System.Web.Http.RoutePrefix("api/account")]
public class AccountController : ApiController
{
// <snip>
/// <summary>
/// Current logged in account.
/// </summary>
// GET api/Account/UserInfo
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[System.Web.Http.Route("userinfo")]
public async Task<UserInfoViewModel> GetUserInfo()
{
ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
var userName = User.Identity.GetUserName();
var account = new AccountRepresentation(await _context
.Accounts
.SingleOrDefaultAsync(acc => acc.Email == userName));
return new UserInfoViewModel
{
Account = account,
UserName = User.Identity.GetUserName(),
Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null,
Roles = await UserManager.GetRolesAsync(User.Identity.GetUserName())
};
}
// </snip>
}
}
(snip comments added by me)
Notice the routing attributes - it's a bit over the top as I'm trying everything, but as far as I can tell this should be ok.
However in the browser console I'm seeing this:
Failed to load resource: the server responded with a status of 404
(not found) http://localhost:49690/api/account/userinfo
The port number is correct for the default controller so unless it's different for the other controllers for some reason, this should be ok as well.
I've been playing with the RouteConfig.cs file which currently looks as follows:
namespace Api
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Api.Controllers" }
).DataTokens.Add("area", "UI");
routes.MapRoute(
name: "api",
url: "api/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Api.Controllers" }
).DataTokens.Add("area", "UI");
}
}
}
The WebApiConfig file looks as follows:
namespace Api
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Web API configuration and services
// Web API routes
// config.MapHttpAttributeRoutes();
// Configure Web API to use only bearer token authentication.
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
//config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
}
}
}
Application_Start() is like this:
namespace Api
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
//UnityConfig.RegisterComponents();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
log4net.Config.XmlConfigurator.Configure();
}
}
}
What else could be missing or wrong that is preventing the API actions being found?
(Let me know if any other code would be helpful)
Other details:
Visual Studio version: Enterprise 2015 update 3
.NET version: 4.6.1
In .Net Core, attribute routing is now enabled by default. However, in MVC5, you are need to set it up. In your route config, add this:
routes.MapHttpAttributeRoutes();
Note that for normal MVC (i.e. not WebAPI) you need this command instead:
routes.MapMvcAttributeRoutes();
Note: MapHttpAttributeRoutes is an extension method in System.Web.Http so you will need a using System.Web.Http; statement.
if you Porting .net Core application from .net mvc you have add WebApiConfig file and register in global file. and it should be like this. First use Route Attribute because you have use Attribute routing.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I'm trying to register multiple routes for Web Pages and for Web API. Here's my config's:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Registration Courses SPA",
url: "Registration/Courses",
defaults: new {controller = "Registration", action = "Index"});
routes.MapRoute(
name: "Registration Instructors SPA",
url: "Registration/Instructors",
defaults: new { controller = "Registration", action = "Index" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
and
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate:"api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Here's how I register them in Global.asax
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
The problem is that Web API routing not working, I'm getting 404 error, unless I register WebAPI routes first then ASP.NET MVC routes not working and Web API routes working.
Like #ChrFin stated in his comments, if you register the Web API routes first your MVC routes should still work because the default Web API route begins with "api".
I had the same problem but it was because we changed the routeTemplate of the default Web API route to {controller}/{id} because we wanted that to be the default because the purpose of our app is to be an api for other apps. In our Global.asax file the Web API routes are registered before the MVC routes, which is the default for any new Web API application. Because "/anything" matches the default Web API route, route handling stops so our MVC routes never get a chance to get matched.
The key point is that route handling stops if a route gets matched - even if there's no matching controller.
To solve our problem we prefixed our MVC routes with "mvc" and registered our MVC routes before the Web API routes.