I want to display a default status page for my web api project (where instead some IIS message is displayed when I start the project). However it seems like I cannot create views in web api (there is no support for ActionResult).
In addition to a status page I will also use this information to create an api documentation page.
How can I achieve displaying html pages in this situation ?
If your default status page is static html, you don't have to use MVC. Just tell WebApi in your Startup.cs that you want to support static resources:
app.UseFileServer();
For creating an API documentation, maybe you could write that file on startup dynamically?
You can create regular controllers and views in a webAPI project the same as any MVC project. Just create a normal controller that does not inherit from ApiController. In your startup.cs make sure to configure at least a default route.
configuration.Routes.MapHttpRoute(
name: "someName",
routeTemplate: "{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Right click and select Add, then you should see controller at the top. Select one of the mvc controllers.
Related
I have an ASP.NET Core 3.1 MVC router question.
When I change index route to [Route("Index")] in HomeController enter image description here, and then enter the url localhost:5000/index in web browser, it works!
But in my ASP.NET Core MVC project, the default startup url is localhost:5000/home/index enter image description here.
Question
How can I change the default startup url to localhost:5000/index?
I wish use localhost:5000/home/login to visit the login function in the HomeController.
Add following route before your default route.
endpoints.MapControllerRoute(
name: "customindex",
pattern: "index",
defaults: new { controller="Home", action="Index"});
});
pattern can support default value but it works with common scenario like controller/action but if you want specific pattern then you have to specify pattern and also set defaults so those will supply as route value in order to identify action to call.
So it's my first time setting up an netcore MVC based application. I've used MVC 4 in the past on plain old asp.net.
So i'm having issues with my routing. My application is an single page application (spa) that is accessible from the home controller on the index action. I can access this controller method fine, and my defaults are set so that this is navigated to at route: /.
I also have a second controller for authentication called AccountController. This controller's methods take and return JSON, rather then views. I can also access the methods on this controller from my application.
The issue i'm having lies in my next controller, which is the start of my API.
As such, i've put it in a folder called api inside my controllers folder. However, no matter what i try, i cannot seem to get the methods on the controller accessible. I have also tried moving it out of the api folder and just having in the route of the controllers folder.
The routing deffinition
app.UseMvc(routes =>
{
routes.MapRoute(
name: "api",
template: "api/{controller=Core}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
I've tried adding and removing the api definition, removing the api part, and adding a template for actions aswel, all to no effect.
The troublesome controller
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I've tried adding [Route(~routing here~)] annotations to this controller and its methods with no success either.
Folder structure
I should also mention that i've tried plenty of URL's to access this controller on:
/api/Core/
/Core/
/api/Core/Get
I've been wracking my brain for the best part of a day trying to get this sorted and i know i'm missing something obvious, i just can't for the life of me work out what it is.
Edit:
I've added a cut-down sample of my project to github at: https://github.com/lexwebb/aspnet-test if anyone would like a complete example
Edit 2
It appears that my example works, i'm going to add things in to see what breaks it
AFAIK, default route requires the {action} using as well.
Instead of "api" default routing, you may to use the following configuration for such type of controllers (RESTFul controller):
[Route("api/[controller]")]
public class CoreController : Controller
{
[HttpGet]
public JsonResult Get()
{
return Json("Dev");
}
}
I found this Routing is ASP.NET Core article useful in the past.
So as it turns out, i had made a mistake in a totally unrelated place. I had renamed my project half way through the beginning stage of development, after i had build scripts in place. This led to the the wrong dll being referenced on the server when the code was ran, a version that had all of my routing EXCEPT the new one, of course.
With the help of several online tutorials, like this one, I am still struggling to add a Web API service to an existing Asp site, that is not MVC.
I added to the project a new item of type Web API Controller Class(v2.1), named it something like AbcController.cs, and VS2015 asked me to put it in the App_Code directory. The default code has handlers for Get, Put etc. Sounded to me like I am on the right track.
I added a default route in Global.asax.cs like in the tutorial:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
This got built after adding a reference to System.Web.Http.Webhost which was not mentioned in the tutorial. Sounded like I was still on the right track.
However, it doesn't work. I run the site in debug and this gives me a 404 Not Found:
http://localhost:54905/api/abc
I tried to run this on the production server with IIS7, of course as a second test web site to not interfere with the version that is in production. However, I ran into the error that the Microsoft.Web.Infrastructure dll could not be found. To fix this, I should install MVC packages, which I don't like for just an experiment.
My questions are:
do I get it right that the URL is in lower case, i.e., not .../api/Abc ?
does this kind of routing work in the debugger?
am I essentially turning the web site into an MVC web site?
is this really the simplest way to add a "REST" service to an existing web site? I only need to implement the POST, read and return some JSON data, and do not need arguments in the URL
I have just started using this tool to define an API and scaffold out the Web API code in .NET. https://visualstudiogallery.msdn.microsoft.com/cadcb820-762c-4514-9817-884b7558aaa9
I have added a RAML contract which creates a bunch of Controllers and Contracts in the solution. I have also run the function to enable the metadata output. When I go to the /raml page I can see the API spec which is great. However, I get two versions of everything, and I'm not sure what to change to prevent it.
For example, in my .raml file, I have a resource called "operators". Using the tools this creates a Controller called "OperatorsController". The baseUri in the .raml definition file is http://localhost:51366/api/ and the MapHttpRoute of the WebApiConfig.Register function is set with a routeTemplate of api/{controller}/{id}. On the /raml page there is an entry for /bookings AND an entry for /api/Bookings. The first one seems to come from the .raml spec and the second from the BookingsController that was created.
Any idea how to prevent the duplicates.It''s the first time I've played around with api creation, so I might be missing something obvious here...
The metadata (dynamically generated raml) captures all your routes. Your WebApi is configured in such a way that you have two different routes for each action/controller. That is reflected in the api console (the picture in your question).
The controllers you created by using the "Add RAML Contract..." command use attribute routing (RoutePrefix and Route attributes in the generated Controller and Actions).
And you also have the default route "api/{controller}/{id}".
Take a look at WebApiConfig.cs and you will find this:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
So for example the OpertatorsController / Get gets invoked by this two different routes:
/operators (using the route configured via attributes)
/api/operators (using the "DefaultApi" route
If you remove the "DefaultApi" route you will only have one route for each action and thus the duplication will go away.
Note: the baseUri is not used at all for the metadata
I have created a folder admin inside controller folder and wrote few controllers in it. I want to access all functions in that controllers in that folder by a url like abc.com/admin//.
I can get it working directly when its put directly in controller folder.
EDIT
WHAT HAVE YOU TRIED?
Just created a folder and wrote normal controllers in it. But I don't know how to route it.
Well, i would suggest, rather than just creating a folder and create controllers inside of it. You should create an Area
When you create an Area in asp.net mvc, it will automatically create folders(controller, model etc) for you. And the routing setup as well.
For more info, please visit
http://www.codeguru.com/csharp/.net/net_asp/mvc/article.php/c20227/Using-Areas-in-ASPNET-MVC-Application.htm
Add a route for the admin controllers in your route config if you want to support that path in the URL. Something like:
routes.MapRoute(
name: "Admin",
url: "admin/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
But #DotNetDreamer is right that Areas are a better solution for the admin functionality of your site.