Mobile Services Help page : custom metho no added - azure-mobile-services

I am creating a Mobile Services backend with a new Controller, which extends ApiController class.
The new methods are not referenced in the help page. Is there anything to do to register the new methods ?

A new route was needed to handle the new methods. The route is added in the WebApiConfig class :
// Use this class to set WebAPI configuration options
HttpConfiguration config = ServiceConfig.Initialize(new ConfigBuilder(options));
config.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Related

WebApi HelpPage api detail page 404, when "api" prefix removed?

.net4.7 + WebApi5.23 + HelpPage5.23.
My WebApiConfig.Register:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
...
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}", //note: there is no "api/" prefix
defaults: new { id = RouteParameter.Optional }
);
}
}
And the index page is worked:
But the api detail page fail(Page not found):
Please help, thank you.
Routing is bound to be getting confused between routing to your MVC controller or your WebApi controller since the are now sharing the same path.
If you need a web page to show, create a new method within the HelpController that returns a new view.
If you need Json returned, you can still create a new method within the HelpController to do that, just change the return type to JsonResult.
Hopefully this gives you enough to understand what's going wrong, and therefore what to google next.

How to use an Area in ASP.NET Core

How do I use an Area in ASP.NET Core?
I have an app that needs an Admin section. This section requires its Views to be placed in that area. All requests that start with Admin/ will need to be redirected to that area.
In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the Startup.cs file (It's best to place it before any non-area route):
In Startup.cs/Configure method:
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
Then make a folder named Areas in the app root and make another named Admin inside the former, also make these folders inside Admin (ViewComponent is optional):
Now we create a controller inside the Controllers folder named AdminController, the content can be like:
[Area("Admin")]
[Route("admin")]
public class AdminController : Controller
{
public AdminController()
{
// do stuff
}
public IActionResult Index()
{
return View();
}
[Route("[action]/{page:int?}")]
public IActionResult Orders()
{
return View();
}
[Route("[action]")]
public IActionResult Shop()
{
return View();
}
[Route("[action]/newest")]
public IActionResult Payments()
{
return View();
}
}
Now in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for views is just like what you have in a non-area Views folder:
Now, you should be good to go!
Question:
What if I want to have another controller inside my Area?
Answer:
Just add another controller beside AdminController and make sure the routes are like the following:
[Area("Admin")]
[Route("admin/[controller]")]
public class ProductsController : Controller
{
public ProductsController()
{
//
}
[Route("{page:int?}")]
public IActionResult Index()
{
return View();
}
}
The important part is [Route("admin/[controller]")]. With that you can keep the style of routing to admin/controller/action/...
In ASP.NET Core 3.0. If you are working with Endpoint patterns, after adding the Area (Right click over project, Add, New Scaffolded Item, Area), you have to add manually routing pattern on startup.cs Configure method. (At this point the generated ScaffoldingReadMe.txt is out of date).
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
"Admin",
"Admin",
"Admin/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
In the Microsoft docs to migrate from ASP.NET CORE 2.2 to 3.0 the suggestion is to:
Replace UseMvc with UseEndpoints.
I encountered some challenges while trying to fix my Area's while simultaneously having Identity to keep working - but the solution below seems to be working for ASP.NET CORE 3.0 :
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllerRoute("areas", "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
Hopefully I could also help you out and reduce the research time :-)
Scaffolding has generated all the files and added the required dependencies.
However the Application's Startup code may required additional changes for things to work end to end.
Add the following code to the Configure method in your Application's Startup class if not already done:
app.UseMvc(routes =>
{
routes.MapRoute(
name : "areas",
template : "{area:exists}/{controller=Home}/{action=Index}/{id?}");
});
Areas Implementation in Routing
First Create Area(Admin) using VS and add the following code into Startup.cs
First Way to Implement:-
Add Controller Login and Index Action and add Following Code, [Area(“Admin”)] is compulsory to add on controller level to perform asp.net areas Routing.
Startup.cs
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Login}/{action=Index}/{id?}"
);
});
Note: Area routing must be placed first with non area routing, area: exists is compulsory to add area routing.
Controller Code:
[Area("Admin")]
public class LoginController : Controller
{
public IActionResult Index()
{
return Content("Area Admin Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Admin
Second Way to Implement Area Routing:-
Add Following code into startup.cs.
app.UseMvc(routes =>
{
routes.MapAreaRoute(
name: "default",
areaName: "Guest",
template: "Guest/{controller}/{action}/{id?}",
defaults: new { controller = "GuestLogin", action = "Index" });
});
Create an Area “Guest”, Add “GuestLogin” Controller and “Index” Action and add the following code into the newly created controller.
[Area("Guest")]
public class GuestLoginController : Controller
{
public IActionResult Index()
{
return Content("Area Guest Login Controller and Index Action");
}
}
This route may be called using http://localhost:111/Guest
Use this pattern in Configure method in Startup.Cs, as its full routing manner:
app.UseMvc(routes =>{
routes.MapRoute(
name: "MyArea",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");});
In Core 3.1 you should use below code in ConfigureServices method:
services.AddMvc(option => option.EnableEndpointRouting = false);
With .net core, following is needed to be added in the startup file if you are adding an area:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}"
);
});
After that you can just simply mark your area and route in the controller, i.e
[Area("Order")]
[Route("order")]
it works for me.
Use this pattern in Configure method in Startup.Cs, as its full routing manner:
app.UseMvc(routes =>{
routes.MapRoute(
name: "MyArea",
template: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");});
In Core 3.1 you should use below code in ConfigureServices method:
services.AddMvc(option => option.EnableEndpointRouting = false);

Web API routing and a Web API Help Page: how to avoid repeated entries

I am getting repeat entries rendered in my Web API Help Page with different parents, such as these, that refer to the same method:
GET api/{apiVersion}/v1/Products - Gets all products
...
GET api/v1/Products - Gets all products
...
I have a Web API page with some routing like this:
config.Routes.MapHttpRoute (
name: "DefaultVersionApi",
routeTemplate: "api/{apiVersion}/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute (
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
I had thought that this routing would make the "v1" optional, so the derived documentation above is not expected.
(sidebar: Going to api/products certainly doesn't work, so I am not sure what is wrong with this. What am I missing?)
It seems the real problem is that Web API Help Page is reading the routes improperly, as I thought v1 and {apiVersion} should not both appear in the same action. What am I missing here?
Try using Attribute Routing, install nuget package
Install-Package Microsoft.AspNet.WebApi.WebHost
Enable Attribute Routing in the WebApiConfig.cs
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 }
);
}
}
Then use the attribute Route in the methods of your Controller
[Route("~/api/v1/Products")]
[HttpGet]
public List<Product> Products()
{}
[Route("~/api/v2/Products")]
[HttpGet]
public List<Product> V2Products()
{}
in the documentation you will get
GET api/v1/Products - Gets all products
GET api/v2/Products - Gets all products
It seems like this is a shortcoming of the ASP.NET Web API help pages. To workaround, I changed the view to exclude these invalid routes from the rendered document. For the above example, I added this Where clause to the loop in ApiGroup.cshtml, changing
#foreach (var api in Model){
to
#foreach (var api in Model.Where(m => !m.Route.RouteTemplate.Contains(#"{apiVersion}"))){

Web API 2.2 Content Negotiation with file extensions

I am working on a Web API and I want to use Content Negotiation with file extensions to allow browser clients to specify the content they want to receive. For instance
http://localhost:54147/data.xslx.
According to this article (http://msdn.microsoft.com/en-us/magazine/dn574797.aspx) I should be able to setup routing with something like this
//setup default routes
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new {id = RouteParameter.Optional}
);
//setup routes with extensions
config.Routes.MapHttpRoute(
name: "Url extension",
routeTemplate: "{controller}/{action}.{ext}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Here is my simple controller
public class TestController : ApiController
{
public HttpResponseMessage Get()
{
var items = new[] {"test1", "test2", "test3"};
return Request.CreateResponse(HttpStatusCode.OK, items);
}
}
using this url
http://localhost:54147/test/get.xlsx
I always get the browser default (xml in chrome, json in IE11).
or possibly
http://localhost:54147/test.xlsx
to which I get the error
No HTTP resource was found that matches the request URI 'http://localhost:54147/test.xlsx'.
I should be able to use my custom formatter. But it's not happening. Here is the constructor of my custom formatter.
public ExcelFormatter()
{
MediaTypeMappings.Add(new UriPathExtensionMapping("xlsx", ContentType.Excel));
SupportedMediaTypes.Add(new MediaTypeHeaderValue(ContentType.Excel));
}
Again according to the article this should help the API Content Negotiator use my custom formatter. I appreciate any help.
As the question is old, but is still without an answer:
Generally this links should help:
How to build media formatter
Microsofts words about content negotiation
To the code in the question:
it seems you need to extend from BufferedMediaTypeFormatter(sync) or MediaTypeFormatter`(async)
you need to make your formatter known to HttpConfiguration.Formatters (link)
You probably want to do this in an config for the complete application.
For testing you could add in to a single ApiController like following.
untested example
public class TestController : ApiController
{
TestController() {
Configuration.Formatters.Add(new ExcelFormatter());
}
public HttpResponseMessage Get()
{
var items = new[] {"test1", "test2", "test3"};
return Request.CreateResponse(HttpStatusCode.OK, items);
}
}
```

ASP.NET Web Api Routing Customization

I have WebApi controllers that end with the "Api" suffix in their names (For ex: StudentsApiController, InstructorsApiController). I do this to easily differentiate my MVC controllers from WebApi controllers. I want my WebApi routes to look similar to
http://localhost:50009/api/students/5 and not http://localhost:50009/api/studentsapi/5.
Currently to achieve this, I am setting up routes like
routes.MapHttpRoute(
name: "GetStudents",
routeTemplate: "api/students/{id}",
defaults: new { controller = "StudentsApi", id = RouteParameter.Optional });
routes.MapHttpRoute(
name: "GetInstructors",
routeTemplate: "api/instructors/{id}",
defaults: new { controller = "InstructorsApi", id = RouteParameter.Optional });
This is turning out to be very cumbersome as I have to add a route for each method in my controllers. I am hoping there should be an easy way to setup route templates that automatically adds the "api" suffix the controller name while processing routes.
Following #Youssef Moussaoui's direction I ended up writing the following code that solved the problem.
public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector(HttpConfiguration configuration)
: base(configuration)
{
}
public override string GetControllerName(HttpRequestMessage request)
{
if (request == null)
throw new ArgumentNullException("request");
IHttpRouteData routeData = request.GetRouteData();
if (routeData == null)
return null;
// Look up controller in route data
object controllerName;
routeData.Values.TryGetValue("controller", out controllerName);
if (controllerName != null)
controllerName += "api";
return (string)controllerName;
}
}
And register it in Global.asax as
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector),
new ApiControllerSelector(GlobalConfiguration.Configuration));
Now that ASP.NET Web API 2 is out, there is a much less cumbersome way to do more complex routing like that you suggested, by using attribute routing.
At the top of your controller just add the following attribute:
[RoutePrefix("api/students")]
public class StudentsApiController : ApiController
{
...
}
And then before each API method:
[Route("{id}"]
public HttpResponseMessage Get(int id)
{
...
}
There is a bit of setup required, but the positives of doing routing this way are many. For one, you can put the routing with the controllers and methods that do the actual work, so you're never searching around wondering if you have the right route. Secondly and more importantly, it's much easier to do more complex routing, like having the controller name different from the route name (like you want) or having very complex patterns to match against.
I think the extensibility point you're looking for is the controller selector. You can create a class that derives from DefaultHttpControllerSelector and overrides the GetControllerName to strip out the "api" part. You can then register this controller selector on your service's configuration Services.
Following Youssef's comment on muruug's answer would look something like this
public class ApiControllerSelector : DefaultHttpControllerSelector
{
public ApiControllerSelector (HttpConfiguration configuration) : base(configuration) { }
public override string GetControllerName(HttpRequestMessage request)
{
return base.GetControllerName(request) + "api";
}
}