امکان تغییر شکل سراسری URLهای تولیدی توسط برنامههای ASP.NET Core 2.2
نویسنده: وحید نصیری
تاریخ: ۱۳۹۷/۱۲/۰۲ ۱۳:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
namespace MvcHealthCheckTest.Controllers
{
public class HomeController : Controller
{
public IActionResult ViewDetails()
{
return View();
} <a asp-controller="Home" asp-action="ViewDetails">View Details</a>
https://localhost:5001/Home/ViewDetails
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Routing;
public class CustomUrlTransformer : IOutboundParameterTransformer
{
public string TransformOutbound(object value)
{
return value == null ? null : Regex.Replace(value.ToString(), "([a-z])([A-Z])", "$1-$2");
}
} namespace MvcTest
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddRouting(option =>
{
option.ConstraintMap.Add(key: "transformer1", value: typeof(CustomUrlTransformer));
option.LowercaseUrls = true;
});
} namespace MvcTest
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// ...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:transformer1}/{action:transformer1}/{id?}",
defaults: new { controller = "Home", action = "Index" }
);
});
} app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller:transformer1=Home}/{action:transformer1=Index}/{id?}"
);
}); https://localhost:5001/home/view-details
وقتی من در asp-route-title مقدار فارسی و با فاصله مینویسم، url موجود در تصویر تولید میشود، که در address bar مثلا میشود «علی%22مجیدی» در صورتی که من میخواهم به جای اون درصد مقدار - باشد.
@using System.Text;
@using System.Text.RegularExpressions;
@functions
{
private static string RemoveAccent(string text) { /* defined in https://www.dntips.ir/post/1529*/ }
public static string GenerateSlug(string title, int maxLenghtSlug = 50) { /* defined in https://www.dntips.ir/post/1529*/ }
}
@{
var value = GenerateSlug("this is a test");
}
<a asp-controller="Home" asp-action="ViewDetails" asp-route-id="@value">View Details</a> public class AnchorTagHelper : TagHelper {
/// <summary>
/// The name of the action method.
/// </summary>
[HtmlAttributeName ("asp-action")]
public string Action { get; set; }
/// <summary>
/// The name of the controller.
/// </summary>
[HtmlAttributeName ("asp-controller")]
public string Controller { get; set; }
/// <summary>
/// The name of the area.
/// </summary>
[HtmlAttributeName ("asp-area")]
public string Area { get; set; }
[HtmlAttributeName ("asp-route")]
public string Route { get; set; }
// Can be async Task
public override void Process (TagHelperContext context, TagHelperOutput output) {
output.TagName = "a";
string result = string.Empty;
if (!string.IsNullOrWhiteSpace (Area)) {
result += "/" + Area;
}
if (!string.IsNullOrWhiteSpace (Controller)) {
result += "/" + Controller;
}
if (!string.IsNullOrWhiteSpace (Action)) {
result += "/" + Action;
}
if (!string.IsNullOrWhiteSpace (Route)) {
Route = ToFriendlyHref (Route);
result += "/" + Route;
}
output.Attributes.SetAttribute ("href", result.ToLowerInvariant ());
//output.Content.SetContent (currentAttribute.ToString ());
}
private string ToFriendlyHref (object value) {
string text = value.ToString ();
List<char> illegalChars = new List<char> () { ' ', '.', '#', '%', '&', '*', '{', '}', '\\', ':', '<', '>', '?', ';', '@', '=', '+', '$', ',' };
illegalChars.ForEach (c => {
text = text.Replace (c.ToString (), "-");
});
return text;
}
} var urlHelper = ViewContext.HttpContext.Items.Values.OfType<IUrlHelper>().FirstOrDefault();
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Routing;
public class CustomUrlTransformer : IOutboundParameterTransformer
{
private static readonly Regex _camelCasingRegEx = new Regex("([a-z])([A-Z])", RegexOptions.Compiled);
public string TransformOutbound(object value)
{
return value == null ? null : _camelCasingRegEx.Replace(value.ToString(), "$1-$2");
}
} app.UseRewriter(new RewriteOptions().Add(new RedirectLowerCaseRule()));
public class RedirectLowerCaseRule : IRule
{
public int StatusCode { get; } = (int)HttpStatusCode.MovedPermanently;
public void ApplyRule(RewriteContext context)
{
HttpRequest request = context.HttpContext.Request;
PathString path = context.HttpContext.Request.Path;
HostString host = context.HttpContext.Request.Host;
if (path.HasValue && path.Value.Any(char.IsUpper) || host.HasValue && host.Value.Any(char.IsUpper))
{
HttpResponse response = context.HttpContext.Response;
response.StatusCode = StatusCode;
response.Headers[HeaderNames.Location] = (request.Scheme + "://" + host.Value + request.PathBase + request.Path).ToLower() + request.QueryString;
context.Result = RuleResult.EndResponse;
}
else
{
context.Result = RuleResult.ContinueRules;
}
}
} if (_options.LowercaseUrls && _options.LowercaseQueryStrings)
{
queryString = queryString.ToLowerInvariant();
}