Routing in ASP.NET Core MVC - asp.net-mvc-3

How can I create a route like this in the url
Localhost:4578//Home/Index/1/2/3/4/5/6
I tried making a custom url using routing in ASP.NET Core 3.1 MVC.

First you cannot use double slash after your port number,
Imagine, you have a CategoryController
Its class name will be like this
[Route("admin/category")]
public class CategoryController : Controller
and after that you will have a method returning ActionResult or something else in this controller
[Route("upper-categories/add")]
public async ActionResult UpperCategoryAdd()
You access this method by using /admin/category/upper-categories/add
and if you want to use an id or something like that
you should use {id} on it
[Route("upper-categories/edit/{id}")]

Related

Can I specify that a controller level request mapping is not valid for a specific method into a Spring MVC controller class?

I am working on a Spring MVC application and I have the following problem into a controller class that is annotated with #RequestMapping("/profilo/") at class level.
So I have something like this:
#Controller
#RequestMapping("/profilo/")
public class ProfiloController extends BaseController {
..................................................................
..................................................................
SOME CONTROLLER METHOD THAT WORK CORRECTLY
..................................................................
..................................................................
#RequestMapping(value = "utenze/{username}/confermaEmail/{email:.+}", method = RequestMethod.GET)
public String confermaModificaEmail(#PathVariable String username, #PathVariable String email, Model model) {
logger.debug("INTO confermaModificaEmail(), indirizzo e-mail: " + email);
.......................................................................
.......................................................................
.......................................................................
}
}
So, as you can see in the previous code snippet, I have this ProfiloController class that is annotated with #RequestMapping("/profilo/") so it means that all the HTTP Request handled by the controller method of this class have to start with the /profilo/ in the URL.
It is true for all the method of this class except for the confermaModificaEmail() method that have to handle URL as:
http://localhost:8080/my-project/utenze/mario.rossi/confermaEmail/a.nobili#siatec.net
that don't tart with /profilo/.
So can I specify that for this specific method of the controller the #RequestMapping("/profilo/") controller level mapping is not valid and have to be not considered?
This is not possible.
Spring has maintained a proper #Controller structure which says for all endpoints related to ControllerName (i.e .Portfolio in your case) should be kept in this class.
Ideally, any other url not related to the functionality should be kept as part of a different Controller class.
If still you want to keep in same controller, try calling the endPoint url confermaModificaEmail() by redirecting the http call from "/portfolio/<"sample"> to the required url. But this is not recommended.

Spring MVC Url Pattern Issue

I have an existing application ..where we have some jsp..in view folder of the
application Context.Now we need to migrate one of the JSP's to a spring mvc controller..
I was doing a sample application and this is what i observed...
if I have the pattern in web-xml as / and annotate the controller as
RequestMapping(value="/view/Track.jsp")
This doesnt work..but If I modify it as /view and
update it as
RequestMapping(value="Track.jsp") then it works..
What is the reason for this..and what should be the approach for the migration.
Spring MVC concatenates the mapping from the controller and the method. With your second mapping it results in: /view/Track.jsp - this is OK. When the mapping on th controller is /view/Track.jsp you probably don't have mapping on the method, right? That way spring don't know which method of the controller to call even if you got only one...
If you want to use only the mapping on the controller you can place #RequestMapping(method = RequestMethod.GET) on the method.
#Controller
#RequestMapping("/view/Track.jsp")
public class UserController {
#RequestMapping(method = RequestMethod.GET)
public String track( MapModel model ) {...}
}
Good practice is to use the mapping on the controller to "modulaize" your mappings if you got more controllers. That way you will prevent collision on the method mappings between controllers.

read Asp.Net Web api GET values from url

I am trying to map /{Controller}/{Variable1}/{Variable2}/{Variable3} to a GET method in controller
public TestController{
public ActionResult Get([FromUrl] Entity instance){}
}
So I need to map variables to the entity.
To put it into an example
/Product/{category}/{filter1}/{filter2}/
Entity
public class ProductSearchRequest
{
public string Category{get;set;}
public string filter1 {get;set;}
public string filter2 {get;set;}
}
Controller
public ProductController: Controller {
public ActionResult GET([FromUri] ProductSearchRequest productSearchRequest){
}
}
[EDITED]
Had to do following changes to get this working
Instead of RouteCollection.MapHttpRoute use HttpConfiguration.Routes.MapHttpRoute as this is API routing not MVC routing.
Inherit controller from ApiController rather than Controller which I was before.
Basically you are not going to be able to do that. Complex types are not compatible with the routing mechanism.
Take a read of this article. But this paragraph explains why the routing mechanism cannot do what you are asking.
A complex type can only bind to the URI through a custom binding. But
in that case, the framework cannot know in advance whether the
parameter would bind to a particular URI. To find out, it would need
to invoke the binding. The goal of the selection algorithm is to
select an action from the static description, before invoking any
bindings. Therefore, complex types are excluded from the matching
algorithm.
Therefore the basic rule is:
For every parameter of the action, if the parameter is taken from the
URI, then the parameter name must be found either in the route
dictionary or in the URI query string. (Optional parameters and
parameters with complex types are excluded.)
Which means you need to define your action like so:
public ActionResult GET(string Category, string filter1, string filter2){
}
And your route template:
/{controller}/{category}/{filter1}/{filter2}/

ASP.NET WebAPI Supported Media Types per Method

Given a method in a controller:
public class CustomerController : ApiController
{
[HttpGet]
public CustomerDto GetById([FromUri] int id)
{
.
.
return customerDto
}
}
Is there a way to specify supported Media Types with an attribute? For instance, CustomerDto is a complex class and will only serialize with JSON (application/json) not XML (application/xml) but could also accept PDF (application/pdf). Is there something like this:
[HttpGet(Accepts.JSON, Accepts.PDF)]
or
[HttpGet][AcceptJSON][AcceptXML]
or
[HttpGet][Accept("application/json")][Accept("application/pdf")]
If the incoming request wasn't supported a Unsupported Exception / Status could be returned.
Note - I don't want to remove say XML serialization all together as could be done globally. Instead, I would like to define what is accepted per route.
Using - ASP.NET WebAPI RC 1 (need to upgrade) + Self Hosting
Sounds like a custom ActionFilterAttribute might do the trick.
Create a new class that inherits from System.Web.Http.Filters.ActionFilterAttribute, override the OnActionExecuting method. Inside this method, you could check the request's headers, look for what you don't want to support and return an appropriate response.
The constructor for your custom ActionFilterAttribute could take the details of which "accept" types you want to process and which ones you want to reject.
For an example of a custom ActionFilterAttribute, check out this post.

FluentValidation validator not being called

I have a MVC 3 site but am using the non-MVC FluentValidation dll. I've created a validator class and in the constructor put all my RuleFors and then set an attribute on my model class thus
[FluentValidation.Attributes.Validator(typeof(MyValidator))]
The problem is that the constructor on the validator class never gets called. I think it might be because I am not using the MVC version of the dll, but then I could not get that version to work for me either.
Any help would be appreciated.
Thanks,
Sachin
In your Application_Start make sure that you have initialized the custom fluent validation model validator provider otherwise nothing will happen:
FluentValidation.Mvc.FluentValidationModelValidatorProvider.Configure();
The FluentValidationModelValidatorProvider class is defined inside the FluentValidation.Mvc assembly. Please take a look at the documentation for integrating FluentValidation into an ASP.NET MVC site.
The validator will be triggered when you invoke a controller action taking a model decorated with the [Validator] attribute as argument:
[HttpPost]
public ActionResult Process(MyViewModel model)
{
...
}
Another reason your validation might not be called is if you have more than one constructor. I did this by accident and it was mystifying. I am so used to having a service constructor just pass in required services from dependency injection, that I did this by mistake:
public MyValidator(IJsonService jsonService)
{
_jsonService = jsonService;
}
public MyValidator()
{
RuleFor(x => x.ProductTechnologyId).GreaterThan(0).NotEmpty();
}
Only one constructor can be called! Oops!

Resources