Noob in ASP MVC Routing - 404 error - c#

I'm new to API designing with VS2017 and I'm trying to make my simple API work with few SQL objects in a DB.
I have a fairly simple project which looks like this :
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 }
);
}
Which I believe is stock so should get me where I want to.
I have some controllers based on the same principles, here's one for example :
public class UsersController : Controller
{
private APIContext db = new APIContext();
// GET: Users
public ActionResult Index()
{
return View(db.Users.ToList());
}
// GET: Users/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Users users = db.Users.Find(id);
if (users == null)
{
return HttpNotFound();
}
return View(users);
}
}
There are more of them, but everything has been autogenerated so I don't think I have to show them.
The problem is that when I get to localhost/api/users, I get the 404 error page :
No HTTP resource was found that matches the request URI 'http://localhost:myport/api/users'.
Same thing when I'm trying to access a specific id with /api/users/1
Can anyone point me where I should try and change things ?
I'm lost in the jungle of the config files and routes !
Thanks !
EDIT :
After some good answers, here's some more information:
I'm wondering if the issue is not somewhere else. When I'm on the localhost/api, I get a "beautiful" error page but when I try to access the /api/users/index I get an XML response with a 404 message in it. Is that a sign of another problem ?
Something to note is that the Swagger UI shows absolutely nothing.

Your Routing configuration mentions only a Controller in the template without a default Action associated with.
Multiple choices are available to you, however, I would suggest to go for a simple one as in:
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 { action = "index", id = RouteParameter.Optional }
);
}
Now the Action is part of the template, with a default value of index, you will have the following:
http://localhost:myport/api/users redirecting to UsersController.Index
http://localhost:myport/api/users/index redirecting to UsersController.Index
http://localhost:myport/api/users/details redirecting to UsersController.Details
http://localhost:myport/api/users/details/123 redirecting to UsersController.Details
Edit After a second investigation, it appears that you are using an MVC Controller rather than a WebApi Controller. While they both have the same name, they belong to different namespaces and need their own config.
In order to configure your MVC controller route, ensure to have a class as follow in your App_Start folder:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
}
Then, from the Global.asax, in Application_Start method, ensure to have the following call:
RouteConfig.RegisterRoutes(RouteTable.Routes);
as in:
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
From this point, you can now access your controller via http://localhost:myport/users.
On the other end, if you want to do an API returning data rather than views, you would need your controller to inherit from ApiController.

Use http://localhost:yourport/users/index" instead.
The URL format is always Controller/Action/Parameters.

Add a new route with {action}
config.Routes.MapHttpRoute(
name: "MyNewRoute",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { type = RouteParameter.Optional }
URL: http://localhost:myport/api/users/details/123456

Related

Routing not working .net mvc api

Did a lot of reading around this but no existing fixes work for me.
I am trying to hit an api endpoint from a apiClient project but I keep getting the error message: No action was found on the controller 'UserApi' that matches the request.
I'm able to debug into the api controller but it just won't hit the method.
Client:
public async Task<bool> UserExists(UserDto dto)
{
var postUrl = $"{BaseUri}UserApi/user-exists";
var json = await PostAsync(new Uri(postUrl), dto);
return JsonConvert.DeserializeObject<bool>(json);
}
Api controller:
[Route("api/UserApi")]
public class UserApiController : ApiController
{
public UserApiController()
{
}
[HttpPost]
[Route("user-exists")]
public async Task<bool> UserExists([FromBody]UserDto dto)
{
return true;
}
Route config:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapHttpRoute(
name: "ApiAction",
routeTemplate: "api/{controller}/{action}/{dto}",
defaults: new { dto = UrlParameter.Optional }
);
}
The bottom routing configuration is the one I'm trying to use. Any help is appreciated
the first comment on the original post solved half my issue - I was trying to configure routing two different ways. I removed all my code from RegisterRoutes and used
config.MapHttpAttributeRoutes();
in WebApiConfig.
I also needed to use the RoutePrefix attribute on the api controller instead of just Route - which is to be used on the controller methods. working now
1.In Global.asax.cs just comment
//RouteConfig.RegisterRoutes(RouteTable.Routes);
As you are using web api no need of this route configuration
2.In WebApiConfig.cs use below line only
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Multiple actions were found that match the request But WebApiConfig is set

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

404 Errors after porting .Net Core application to MVC

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

Multiple actions were found that match the request when using actions in Route config

I'm currently building an API using Web API 2.2
I have the RESTful part of it working but now I need one non-RESTful controller:
public class PremisesController : ApiController
{
private PremiseService _service;
public PremisesController()
{
_service = new PremiseService();
}
[HttpGet]
public IHttpActionResult Premise(string id)
{
id = id.Replace(" ", String.Empty).ToUpper();
List<Premise> premises = _service.GetPremisesForPostcode(id);
return Ok(premises);
}
[HttpGet]
public IHttpActionResult Building(string id)
{
double premise = Convert.ToDouble(id);
Building building = _service.GetBuildingsForPremise(premise);
return Ok(building);
}
}
The routing config is as follows:
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 }
);
Im getting the error that it can't distinguish between the two methods when I initiate a GET action:
Multiple actions were found that match the request
So my question is Do I need to specify the Route attribute on top of each method and if yes, why? Doesn't the second route (ActionApi) deals with that situation?
EDIT:
I just tested you're code and it works the way it is... maybe just it is unclear.
/api/Premises/Premise/8 --> will take you to your first action
/api/Premises/Building/8 --> will take you to your second action
/api/Premises/8 --> will cause error because the routing will go to the first rule api/{controller}/{id} with a GET request, then he can't distinguish which of the actions you want because they both match the first route: (api/Premises/{id})
You could also use the RoutePrefix attribute on your controller.
[RoutePrefix("api/premises")]
public class PremisesController : ApiController
That combined with the route attribute would mean you shouldn't get multiple actions with the same route

Creating a WebService inside my MVC project

I know there's another thread about WebapiConfig.cs and RouteConfig.cs, but I can assure this is a different question.
My MVC project was quite developed by the time I found out I would have to create a webservice (in the same domain) where I would grant access to one of my models (both in JSON and XML).
In order to do so, I right clicked over my Controllers and selected "add Web API 2 Controller with actions, using Entity Framework" and selected also my model class and db context.
The template was quite complete and I thought I was ready to go for the following test:
namespace MVC4GMAPS.Controllers
{
public class RestController : ApiController
{
private LocationDBContext db = new LocationDBContext();
// GET api/Rest
public IQueryable<Location> GetLocations()
{
return db.Locations;
}
etc...
Unfortunately, when I tried to access to https://localhost:44300/api/Rest I've got a 404. However, localhost:44300/Home/Index keeps working great.
I believe the problem relies on my RouteConfig.cs, because it is expecting an {action} and my RestController doesn't have any actions:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
etc...
What can I do? Can I create simultaneously a WebapiConfig.cs file? I believe not. I hope you can help me!
Do you also have a WebApiConfig.cs? In a project which was "Web API from the start" I have this in it:
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 }
);
}
}
This, like the other configs, is called from Global.asax.cs:
GlobalConfiguration.Configure(WebApiConfig.Register);
That should get the routing pointed to the API controller. Otherwise, as you say, the route defined from MVC by default would be looking for an action called Rest on a controller called api which doesn't exist.

Categories