I'm reading through Adam Freeman's Pro ASP.NET Core MVC 2 and one of the chapters about advanced routing features includes a mechanism whereby you can implement two-way legacy URL handling via IRouter. The gist of it is this:
Suppose you have a "legacy" URL like "/article/Windows_3.1_Overview.html"
Using a custom IRouter implementation, Core 2.0 lets you:
Direct that legacy URL to a specific action (e.g. Legacy/GetLegacyUrl) while passing in the URL as a parameter as so:
public async Task RouteAsync(RouteContext context)
{
string requestedUrl = context.HttpContext.Request.Path.Value.TrimEnd('/');
if (urls.Contains(requestedUrl, StringComparer.OrdinalIgnoreCase))
{
context.RouteData.Values["controller"] = "Legacy";
context.RouteData.Values["action"] = "GetLegacyUrl";
context.RouteData.Values["legacyUrl"] = requestedUrl;
await mvcRoute.RouteAsync(context); // mvcRoute is an instance of MvcRouteHandler
}
}
Generate that same URL using a tag helper: (<a asp-route-legacyurl="/article/Windows_3.1_Overview.html">Old Link</a>) using the following:
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
if (context.Values.ContainsKey("legacyUrl"))
{
string url = context.Values["legacyUrl"] as string;
if (urls.Contains(url))
{
return new VirtualPathData(this, url);
}
}
return null;
}
My question is: how do I do that in Core 3.0? I've tried this approach but there is no MvcRouteHandler anymore. I've tried implementing DynamicRouteValueTransformer like so:
public async override ValueTask<RouteValueDictionary> TransformAsync(HttpContext httpContext,
RouteValueDictionary values)
{
string requestedUrl = httpContext.Request.Path.Value.TrimEnd('/');
return await Task.FromResult(new RouteValueDictionary()
{
["controller"] = "Legacy",
["action"] = "GetLegacyUrl",
["legacyUrl"] = requestedUrl
});
}
... but as far as I've read, this only works one way. It's also the only thing mentioned in Microsoft's 2.2 -> 3.0 migration guide. I've tried to just literally map the URL using
routes.MapRoute(
name: "",
template: route,
defaults: new { controller = "Legacy", action = "GetLegacyUrl", legacyUrl = route });
But this also doesn't generate the legacy URL, instead opting for Legacy/GetLegacyUrl/?legacyUrl=%2Farticle%2FWindows_3.1_Overview.html
I'm not really sure how else I can achieve this and I've been racking my brain and the documentation for several hours now. "Routing in ASP.NET Core" didn't help, neither did "Migrate from ASP.NET Core 2.2 to 3.0".
I'm probably missing something obvious, but I just can't seem to find an answer.
You could get the default mvc route handler using routes.DefaultHandler
In LegacyRoute.cs file, change your constructor signature from
public LegacyRoute(IServiceProvider services, params string[] targetUrls)
To
public LegacyRoute(IRouter routeHandler, params string[] targetUrls)
In Startup.cs file, add the route like this given below
routes.Routes.Add(new LegacyRoute(routes.DefaultHandler, "/articles/Windows_3.1_Overview.html", "/old/.NET_1.0_Class_Library"));
Related
I'm writing an app using WebAssembly Blazor hosted by ASP.NET Core. Some of pages are implemented in Blazor, but some old pages are still ASP.NET Core Razor views. I need to create a link in Blazor component pointing to action of controller on server.
I can write:
NavigationManager.NavigateTo("SomeContoller/SomeAction/123", true)
But I don't want to hardcode url to action, because changing server routing or contoller/action names will break such links. Is there any way to create proper links via some helper, similar to ASP.Net Core UriHelper? Like:
UriHelper.Action("SomeAction", "SomeController", new {id = 123});
In Blazor server apps you can use LinkGenerator. The usage is not much different that of UriHelper:
#using Microsoft.AspNetCore.Routing
#inject LinkGenerator LinkGenerator
Sign in
ReSharper understands this one too, so you will get auto-completion for controller and action names.
In WebAssembly apps LinkGenerator is not available, so your best bet is to dump all routes from the server and implement your own link generator which uses that data on the client (its complexity depends on complexity of your routes, the one from ASP.NET Core is quite complex).
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
namespace BlazorTest.Server.Controllers
{
[Route("api/routes")]
[ApiController]
public class RouteInformationController : ControllerBase
{
private readonly EndpointDataSource _endpointDataSource;
public RouteInformationController(EndpointDataSource endpointDataSource)
{
_endpointDataSource = endpointDataSource;
}
public IEnumerable<object> Get()
{
foreach (var endpoint in _endpointDataSource.Endpoints.OfType<RouteEndpoint>())
{
var actionDescriptor = endpoint.Metadata.GetMetadata<ControllerActionDescriptor>();
if (actionDescriptor == null)
continue;
yield return new
{
actionDescriptor.ControllerName,
actionDescriptor.ActionName,
Parameters = actionDescriptor.Parameters.Select(p => p.Name),
RoutePattern = endpoint.RoutePattern.RawText,
};
}
}
}
}
You can create a static class with constant properties in it for all the URLs that you use in the app. After that use the same static class property in both the page route and your navigation route. Below is a very basic version of this:
public static class RouteUrls
{
public static string Home = "/Home";
public static string ProductList = "/Product";
public static string ProductDetail = "/Product/Detail";
public static string SomePage = "/SomeContoller/SomeAction";
}
// to access it use like this:
NavigationManager.NavigateTo($"{RouteUrls.SomePage}/123", true)
This question is a follow up to this post - How to perform async ModelState validation with FluentValidation in Web API?.
I was wondering if FluentValidation has a way to perform async ModelState validation in .net core web api. I have a FluentValidation Validator class which contains async validation methods such as "MustAsync", which means in my business service class I call the validator manually using "ValidateAsync". I also want to use this same validator class to validate the model coming in from the request. I went through the documents and read that the only way to do this is to manually call the "ValidateAsync()" method since the .net pipeline is synchronous. I would rather not manually have to call this method from within my controller, I would prefer to either register it in the startup (have the framework automatically call the the validator on my model) or decorate my request model with the validator.
Has anyone been able to achieve this?
Thanks!
Based on the linked question, I've adapted the code slightly to be compatible with ASP.NET Core (2.2, in my case). In general, this is using the IAsyncActionFilter interface. You can read about it in the official docs.
public class ModelValidationActionFilter : IAsyncActionFilter
{
private readonly IValidatorFactory _validatorFactory;
public ModelValidationActionFilter(IValidatorFactory validatorFactory) => _validatorFactory = validatorFactory;
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
var allErrors = new Dictionary<string, object>();
// Short-circuit if there's nothing to validate
if (context.ActionArguments.Count == 0)
{
await next();
return;
}
foreach (var (key, value) in context.ActionArguments)
{
// skip null values
if (value == null)
continue;
var validator = _validatorFactory.GetValidator(value.GetType());
// skip objects with no validators
if (validator == null)
continue;
// validate
var result = await validator.ValidateAsync(value);
// if it's valid, continue
if (result.IsValid) continue;
// if there are errors, copy to the response dictonary
var dict = new Dictionary<string, string>();
foreach (var e in result.Errors)
dict[e.PropertyName] = e.ErrorMessage;
allErrors.Add(key, dict);
}
if (allErrors.Any())
{
// Do anything you want here, if the validation failed.
// For example, you can set context.Result to a new BadRequestResult()
// or implement the Post-Request-Get pattern.
}
else
await next();
}
}
If you want to apply this filter globally, you can add the filter to the AddMvc call in your Startup class. For example:
services.AddMvc(options =>
{
options.Filters.Add<ModelValidationActionFilter>();
// uncomment the following line, if you want to disable the regular validation
// options.ModelValidatorProviders.Clear();
});
I had trouble getting the code in #nachtjasmin's answer to work with newer versions of FluentValidation. Specifically, the trouble is that ValidateAsync now takes an IValidationContext instead of the model being validated, and the context can't be created without knowing the type of the model at compile time.
Eventually I stumbled upon this answer, which points out that the exact type is not important and uses object instead.
So, instead of:
var result = await validator.ValidateAsync(value);
You can use:
var context = new ValidationContext<object>(value);
var result = await validator.ValidateAsync(context);
Based on the answer above by #nachtjasmin, you can add this in two ways,
Using AddMvc
services.AddControllersWithViews(options =>
{
options.Filters.Add<FluentValidationActionFilter>();
});
Using AddControllersWithViews
services.AddControllersWithViews(options =>
{
options.Filters.Add<FluentValidationActionFilter>();
});
If your's is just a Web API and you don't have any Razor pages involved, then you can consider using AddControllersWithViews over AddMvc, as the AddMvc uses the AddControllersWithViews internally and add the services.AddRazorPages() on top of that.
You can see this info here for AddMvc and here for AddControllersWithViews
Upgrading to asp.net core 2.2 in my hobby project there is a new routing system I want to migrate to. Previously I implemented a custom IRouter to be able to set the controller for the request dynamically. The incoming request path can be anything. I match the request against a database table containing slugs and it looks up the a matching data container class type for the resolved slug. After that I resolve a controller type that can handle the request and set the RouteData values to the current HttpContext and passing it along to the default implementation for IRouter and everything works ok.
Custom implementaion of IRouter:
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
var page = _pIndex.GetPage(requestPath);
if (page != null)
{
var controllerType = _controllerResolver.GetController(page.PageType);
if (controllerType != null)
{
var oldRouteData = context.RouteData;
var newRouteData = new RouteData(oldRouteData);
newRouteData.Values["pageType"] = page.PageType;
newRouteData.Values["controller"] = controllerType.Name.Replace("Controller", "");
newRouteData.Values["action"] = "Index";
context.RouteData = newRouteData;
await _defaultRouter.RouteAsync(context);
}
}
}
A controller to handle a specific page type.
public class SomePageController : PageController<PageData>
{
public ActionResult Index(PageData currentPage)
{
return View("Index", currentPage);
}
}
However I got stuck when I'm trying to figure out how I can solve it using the new system. I'm not sure where I'm suppose to extend it for this behavior. I don't want to turn off the endpoint routing feature because I see an opportunity to learn something. I would aso appreciate a code sample if possible.
In ASP.NET 3.0 there is an new dynamic controller routing system. You can implement DynamicRouteValueTransformer.
Documentation is on the way, look at the github issue
Can we use dashes (-) in the Route template in ASP.NET Core?
// GET: api/customers/5/orders?active-orders=true
[Route("customers/{customer-id}/orders")]
public IActionResult GetCustomerOrders(int customerId, bool activeOrders)
{
.
.
.
}
(The above code doesn't work)
The route parameters usually directly map to the action's variable name, so [Route("customers/{customerId}/orders")] should work since that's the name of your variable (int customerId).
You don't need dashes there, the part within the curly braces {} will never appear as a part of the generated url, it will always be replaced by the content you pass from browser or the variables you pass to the url generator.
customers/{customerId}/orders will always be customers/1/orders when customerId is set to 1, so there's no point trying to force it to {customer-id}.
However, you can try public
[Route("customers/{customer-id}/orders")]
IActionResult GetCustomerOrders([FromRoute(Name = "customer-id")]int customerId, bool activeOrders)
to bind the customerId from a unconventional route name, if you wish. But I'd strongly advise against it, as it just adds unnecessary code which has absolutely zero-effect on your generated urls.
The above generates (and parses) the exactly same url as
[Route("customers/{customerId}/orders")]
IActionResult GetCustomerOrders(int customerId, bool activeOrders)
and is much more readable code.
For the query part, as you figured it out in the comments, it makes sense to add the dashes via [FromQuery(Name = "active-orders")] bool activeOrders, since that really affects the generated url.
New in ASP.NET Core 2.2
In ASP.NET Core 2.2 you'll get a new option to 'slugify' your routes (only supported when using the new Route Dispatcher instead of the default Mvc Router).
A route of blog\{article:slugify} will (when used with Url.Action(new { article = "MyTestArticle" })) generate blog\my-test-article as url.
Can also be used in default routes:
routes.MapRoute(
name: "default",
template: "{controller=Home:slugify}/{action=Index:slugify}/{id?}");
For further details see the ASP.NET Core 2.2-preview 3 annoucement.
Just expanding on Tseng answer to the question. for ASP NET CORE to use "slugify" transformer you need to register it first like so:
public class SlugifyParameterTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
if (value == null) { return null; }
return Regex.Replace(value.ToString(),
"([a-z])([A-Z])",
"$1-$2",
RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(100)).ToLowerInvariant();
}
}
and then in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddRouting(options =>
{
options.ConstraintMap["slugify"] = typeof(SlugifyParameterTransformer);
});
}
Code from Microsoft
I have an OData (v3) Web API 2 project that is a wrapper to another wcf web service. The intended client for this odata connection is SharePoint 2013. I am creating CRUD operations within this wrapper and noticed that when sharepoint is asked to delete something it send a request in this format: /Entity(Identity=XX) instead of it's normal /Entity(XX) that i have working normally. I need to be able to handle that request without breaking the other one. Here is my code:
public IHttpActionResult GetSchool([FromODataUri] int key, ODataQueryOptions<School> queryOptions)
{
// validate the query.
try
{
queryOptions.Validate(_validationSettings);
}
catch (ODataException ex)
{
return BadRequest(ex.Message);
}
SchoolDataSource data = new SchoolDataSource();
var result = data.GetByID(key);
return Ok<School>(result);
//return StatusCode(HttpStatusCode.NotImplemented);
}
This works fine for a request for /Schools(1), but not for /Schools(ID=1). i have tried adding:
[Route("Schools(ID={key}")]
And this makes the /Schools(ID=1) route work, but breaks pretty much everything else (406 Errors). i tried adding the above attribute and
[Route("Schools({key})")]to see if i can get them both working, but it doesn't function correctly either. I am very new to this, and was hoping to at least get some direction. Here is my WebApiConfig:
config.MapHttpAttributeRoutes();
config.EnableQuerySupport();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Web API configuration and services
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<School>("Schools");
builder.DataServiceVersion = new Version("2.0");
config.Routes.MapODataRoute("odata", null, builder.GetEdmModel());
// Web API routes
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Errors i get:
406 if i have the route attribute set. 500 if i dont have the route attribute set. it seems as though my service has no idea how to handle the parameter unless i specify it, but if i do, all calls get 406 errors.
may not be the best approach, but made it work with this class:
public class SharePointRoutingConvention : EntitySetRoutingConvention
{
public override string SelectAction(ODataPath odataPath, HttpControllerContext context,
ILookup<string, HttpActionDescriptor> actionMap)
{
//Gets the entity type
IEdmEntityType entityType = odataPath.EdmType as IEdmEntityType;
//makes sure the format is correct
if (odataPath.PathTemplate == "~/entityset/key")
{
//parses out the path segment (Identity=X)
KeyValuePathSegment segment = odataPath.Segments[1] as KeyValuePathSegment;
//Gets the verb from the request header
string actionName = context.Request.Method.ToString();
// Add keys to route data, so they will bind to action parameters.
KeyValuePathSegment keyValueSegment = odataPath.Segments[1] as KeyValuePathSegment;
//Checks to see if the "Identity=" part is in the url
if (keyValueSegment.Value.Contains("Identity="))
{
//removes the extra text
context.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value.Replace("Identity=", "");
}
else
{
//parses it normally
context.RouteData.Values[ODataRouteConstants.Key] = keyValueSegment.Value;
}
//returns the verb
return actionName;
}
// Not a match.
return null;
}
}
and make the change to the webapiconfig:
var conventions = ODataRoutingConventions.CreateDefault();
//adding the custom odata routing convention
conventions.Insert(0, new SharePointRoutingConvention());
config.Routes.MapODataRoute(
routeName: "odata",
routePrefix: null,//this is so that you can type the base url and get metadata back (http://localhost/)
model: builder.GetEdmModel(),
pathHandler: new DefaultODataPathHandler(),
routingConventions: conventions //this assigns the conventions to the route
);