ASP.NET Core: Many routes -> always only one controller - asp.net-core

Similar to SO ASP.NET MVC: Many routes -> always only one controller:
O have a .net 4.7 MVC project project
my config route are as follows (following from the above post)
config.Routes.MapHttpRoute(
name: "AllRoutes",
routeTemplate: "{*url}",
defaults: new
{
controller = "base",
});
my base controller in my .net 4.7 project
public class BaseController : ApiController
{
[HttpGet]
public IHttpActionResult Get(HttpRequestMessage request)
{
return Ok();
}
[HttpPost]
public IHttpActionResult Post(HttpRequestMessage request)
{
return Ok();
}
[HttpPut]
public IHttpActionResult Put(HttpRequestMessage request)
{
return Ok();
}
[HttpDelete]
public IHttpActionResult Delete(HttpRequestMessage request)
{
return Ok();
}
}
now I'm porting my project into a .NET Core 2.0
I can't seem to setup the same thing
my config in the .net core project is as follows
app.UseMvc(routes =>
{
routes.MapRoute(
name: "AllRoutes",
template: "{*url}",
defaults: new
{
controller = "Base"
}
);
my base controller for my .net core project
//[Route("api/[controller]")]
public class BaseController : Controller
{
[HttpGet]
public IActionResult Get()
{
return Ok("get success");
}
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]string value)
{
return Ok("post success");
}
[HttpPut]
public IActionResult Put([FromBody]string value)
{
return Ok("put success");
}
[HttpDelete]
public IActionResult Delete()
{
return Ok("delete success");
}
}
any ideas?

Why do you even want to use MVC, when you have no controllers or routes?
Just use a custom middleware:
// Startup configure
app.Use(async (context, next) =>
{
var service = context.RequestServices.GetRequiredServce<MyService>();
var service.Execute();
async next();
});
Update
Just in case it's not clear, you can inject IHttpContextAccessor in your service, where you can directly access the request stream and do whatever you need to do with it.

public class BaseContoller : Controller {
[HttpGet("/base/get")]
public IActionResult Get() {
return Ok("get success");
}
[HttpPost("/base/post")]
public IActionResult Post() {
return Ok("post success");
}
}
you looking for something like this?

or if you want to route this links you need add something like this
public class BaseController : Controller {
[Route("/get")]
public IActionResult Get() {
return Ok("get success");
}
}

Related

asp.net core 2.1 odata use different name of entity in the route

I have a long name of of entity in my code EmployeTraining which used as entity in OData and with same name for the controller.
Startup.cs
app.UseMvc(routeBuilder=>
{
routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1", EdmModelBuilder.GetEdmModelEmploye());
});
EdmModelBuilder.cs
public static IEdmModel GetEdmModelEmployes()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<EmployeTraining>("EmployeTraining");
return builder.GetEdmModel();
}
EmployeTrainingControllers.cs
public class EmployeTrainingController : ODataController
{
internal IEmployeService ServiceEmploye { get; set; }
public EmployesController(IEmployeService serviceEmploye)
{
ServiceEmploye = serviceEmploye;
}
//// GET api/employes
[HttpGet]
[MyCustomQueryable()]
public IQueryable<EmployeTraining> Get()
{
return ServiceEmploye.GetListeEmployes();
}
}
To call my service it works only through this URL: https://{server}/odata/v1/rh/employetraining
but I need to use this https://{server}/odata/v1/rh/employe-training
any help please.
For such scenario,change like below:
1.Change the entityset name:
public static class EdmModelBuilder
{
public static IEdmModel GetEdmModelEmployes()
{
var builder = new ODataConventionModelBuilder();
builder.EntitySet<EmployeTraining>("employe-training");
return builder.GetEdmModel();
}
}
2.Add the attribute:
public class EmployeTrainingController : ODataController
{
[HttpGet]
[ODataRoute("employe-training")]
//[MyCustomQueryable()]
public IQueryable<EmployeTraining> Get()
{
return ServiceEmploye.GetListeEmployes();
}
}
3.Startup.cs:
app.UseMvc(routeBuilder=>
{
routeBuilder.Expand().Select().Count().OrderBy().Filter().MaxTop(null);
routeBuilder.MapODataServiceRoute("EmployeTraining", "odata/v1/rh", EdmModelBuilder.GetEdmModelEmploye());
});
Request the url:https://{server}/odata/v1/rh/employe-training
The Reason why is working using https://{server}/odata/v1/rh/employetraining is because is the Get method of the EmployeTrainingController Controller.
You should be able to change that behaibour if you modify the [HttpGet] on the Get method to [HttpGet("employe-training")]

Can't change destination controller/action via IRouter

I have simple MyRouter:
public class MyRouter : IRouter
{
private readonly IRouteBuilder _routeBuilder;
public MyRouter(IRouteBuilder routeBuilder)
{
_routeBuilder = routeBuilder;
}
public async Task RouteAsync(RouteContext context)
{
if (ShouldReroute(...))
{
SetNeededPath(context, reroute);
}
await GetDefaultRouter().RouteAsync(context);
}
private bool ShouldReroute(...)
{
return true;
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
return GetDefaultRouter().GetVirtualPath(context);
}
private IRouter GetDefaultRouter()
{
return _routeBuilder.DefaultHandler;
}
private void SetNeededPath(RouteContext context, Reroute reroute)
{
context.RouteData.Values.Clear();
context.RouteData.Values["action"] = "StoreContacts";
context.RouteData.Values["controller"] = "Information";
}
}
As you can see it should change the destination of the request to:
[Route("")]
public class InformationController : Controller
{
[Route("StoreContacts")]
public IActionResult StoreContacts()
{
return View();
}
}
The routers description in Startup.cs is:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areas",
template: "{area:exists}/{controller=Home}/{action=Index}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.Routes.Add(new MyRouter(routes));
});
So in my brain, it should redirect all unmapped requests like mysite.com/unexistingRoute should go to InformationController.StoreContacts, but I get only 404.
Also the mysite.com/StoreContacts is available via the direct URL.
Attribute routing will take over conventional routing , so you can remove the attribute routing :
public class InformationController : Controller
{
public IActionResult StoreContacts()
{
return View();
}
}
And move your logic into custom route via IRouter . mysite.com/unexistingRoute won't map to existed route template config in Startup.cs . So remove attribute should work in your scenario . To map other url like mysite.com/OtherAction , you can write custom logic like :
if (context.HttpContext.Request.Path.Value.StartsWith("/StoreContacts"))
{
context.RouteData.Values["controller"] = "Information";
context.RouteData.Values["action"] = "StoreContacts";
}

.Net Core 2.0 Web API controller not working and getting 404

I have something very very strange. I have 2 controllers. UploadController and AccountController. Theye were both working, and now when I try the AccountController it give error 404. ik don't get it.
This is how my AccountController looks like:
namespace CoreAngular.Controllers
{
//[Authorize]
[Produces("application/json")]
[Route("api/account")]
public class AccountController : Controller
{
private IRepository repository;
public AccountController(IDatabaseClient<DocumentClient> client)
: this ( new UserRepository(client))
{
}
public AccountController(IRepository repository)
{
this.repository = repository;
}
[HttpGet]
public async Task<ActionResult> Get(string id)
{
var start = DateTime.Now.TimeOfDay;
if (string.IsNullOrEmpty(id))
{
return BadRequest();
}
var user = await repository.GetAsync(id);
if (user == null)
{
return NotFound();
}
var userDTO = new UserGetDTO()
{
image = Convert.ToBase64String(user.image.image),
id = user.id,
time = DateTime.Now.Subtract(start).Millisecond
};
return Ok(userDTO);
}......
Do I miss something here? I know I comentet out the [Authorize], but i just wanted to try to connect.
You should specify route template in HttpGet attribute:
[HttpGet("{id}")]
public async Task<ActionResult> Get(string id)
{
// ...
}

Swashbuckle not displaying methods that have a collection as a paramater

I have a Web API (WebApi 2). I am trying to use Swashbuckle for documentation. I have a GET method that takes a List as a paramater. The method works but does not show up in the Swashbuckle documentation.
[RoutePrefix("myroute")]
public class MyController : ApiController
{
[HttpGet]
[Route("{foo}/{bar}")]
public async Task<IHttpActionResult> Get([FromUri]List<string> foo, string bar)
{
return Ok();
}
}
How do I get a List or array to work with Swashbuckle?
UPDATE
Here is my swagger config:
public class SwaggerConfig
{
public static void Register(HttpConfiguration config)
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
config
.EnableSwagger(c =>
{
c.SingleApiVersion("v1", "ZipCodeWebApi.API");
c.IncludeXmlComments(string.Format(#"{0}\App_Data\ZipCodeWebApi.API.XML", System.AppDomain.CurrentDomain.BaseDirectory));
c.DescribeAllEnumsAsStrings();
})
.EnableSwaggerUi(c =>
{
});
}
}
As you are already saying [FromUri], your action method will show up in swagger only if you remove the Route attribute.
[HttpGet]
public async Task<IHttpActionResult> Get([FromUri]List<string> foo, string bar)
{
return Ok();
}

WebApi for Email delivery

I created a Web API controller inside my ASP.NET MVC 4 Website to specifically send emails so that I can consume it for this purpose and eventually provide it to other consumers (Mobile, etc).
Everything is working fine but I want to use it asynchronously, altough it's not working that way, my website blocks until the work is finished.
I have a regular Controller where I call a helper class that calls the API.
Controller Code :
[HttpPost]
public async Task<ActionResult> ContactUs(ContactUsModel model)
{
ExternalApiCalls extApi = new ExternalApiCalls();
await extApi.PostContactUs(model).ConfigureAwait(false);
return RedirectToAction("ContactUsSuccess", "Account");
}
Helper Class Code :
public class ExternalApiCalls
{
public HttpClient client { get; set; }
public ExternalApiCalls()
{
client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:10239/");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task PostContactUs(ContactUsModel model)
{
try
{
var response = await client.PostAsJsonAsync("api/WAPIMail", model).ConfigureAwait(false);
}
catch (HttpRequestException ex)
{
}
catch (System.FormatException)
{
}
finally
{
}
}
}
Web API Controller :
public class WAPIMailController : ApiController
{
public void PostContactUs(ContactUsModel model)
{
// Send Email Here
}
}
Thanks a lot for your help
I finally managed how to do it..
For brevity's sake, I am showing oversimplified code, see below:
Controller :
[HttpPost]
public ActionResult ContactUs(ContactUsModel model)
{
new ExternalApiCalls().MailContactUs(model);
return RedirectToAction("ContactUsSuccess", "Account");
}
Helper Class :
public void MailContactUs(ContactUsModel model)
{
client.PostAsJsonAsync("api/WAPIMail/MailContactUs", model).ConfigureAwait(false);
}
Web API Controller :
[HttpPost]
public void MailContactUs(ContactUsModel model)
{
//Email Logic Here
}