当前位置:网站首页>Shallow understanding Net core routing
Shallow understanding Net core routing
2022-07-07 16:59:00 【Old sentencing】
route :
web When your request arrives at the back-end service ,controller( controller ) Will process incoming http Request and respond to user actions , Requested url Will be mapped to the operation method of the controller .
This mapping process is done by the routing rules defined in the application .
ASP.NET.Core MVC The routing
Routing uses a pair of UseRouting and UseEndPoints Registered middleware :
UseRouting Add route matching to middleware pipeline . This middleware will view the endpoint set defined in the application , And select the best match according to the request
UseEndpoints Add endpoint execution to the middleware pipeline .
asp.net.core There are two routing technologies : General routing and attribute routing
General routing :
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
Default routing template {controller=Home}/{action = Index}/{id?}
, Most of the URL Will map according to this rule . Question mark id Parameters are optional .
If you want to define your own path template , To use UseMvc() Method , instead of UseMvcWithDefaultRoute() Method .
app.UseMvc(routes =>
{
routes.MapRoute("default","{controller=Home}/{action = Index}/{id?}");
});
//1、 Enable default routing
app.UseStaticFiles();
app.UseRouting();
app.UseMvcWithDefaultRoute();
//2、 Custom routing template
app.UseStaticFiles();
app.UseRouting();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//3、 Use UseEndpoints Custom routing template
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
Attribute routing :
Use attribute routing , Can be in Controller or Controller The operation method of Route attribute .
stay Startp.cs file Configure In the method , We only use app.UseMvc(); And then in Controller Of Action Methodically, through features Route To configure the .
[Route("[controller]/[action]")]
public class HomeController : Controller
{
private readonly IStudentRepository _studentRepository;
// Constructor injection
public HomeController(IStudentRepository studentRepository)
{
_studentRepository = studentRepository;
}
[Route("")]
[Route("~/")] // solve http://localhost:44338/ Can't access the problem
[Route("~/home")] // solve http://localhost:44338/home Can't access the problem
public IActionResult Index(int id)
{
return Json(_studentRepository.GetStudent(id));
}
[Route("{id?}")]
public IActionResult Details(int? id)
{
Student model = _studentRepository.GetStudent(id??1);
return View(model);
}
public ObjectResult detail()
{
return new ObjectResult(_studentRepository.GetStudent(1));
}
}
Examples used in practical projects --- Download the file
[ApiExplorerSettings(IgnoreApi = true)]
public class DownFileController : Controller
{
private ILogger _logger;
/// <summary>
/// download Pscan file
/// </summary>
/// <param name="taskId"></param>
/// <param name="DownloadFilePath"></param>
/// <param name="fileNameList"></param>
/// <returns></returns>
[Route("[Controller]/{taskId}/{DownloadFilePath?}/{fileName?}")]
public IActionResult GetDownFileMessage(string taskId, string DownloadFilePath, string fileName)
{
try
{
if (fileName != null)
{
// Remote deployment
//string path = "/home/ftp_flow/Data/TaskData/" + taskId + "/" + DownloadFilePath;
//string zipPath = "/Data/PscanDownFile/" + $"{DownloadFilePath+"/"+fileNameList}.zip";
// Local debugging
string path = @"E:\beijingData\TaskData\" + taskId + "/" + DownloadFilePath;
Console.WriteLine(path);
var filePath = Path.Combine(path, fileName);
if (System.IO.File.Exists(filePath))
{
Console.WriteLine(filePath);
string fileExt = Path.GetExtension(filePath);
// retrievable ContentType
var provider = new FileExtensionContentTypeProvider();
var memi = provider.Mappings[fileExt];
var stream = System.IO.File.OpenRead(filePath);
Console.WriteLine("success");
return File(stream, memi, Path.GetFileName(filePath));
}
else
{
return NotFound();
}
}
else
{
return NotFound();
}
}
catch (Exception ex)
{
return NotFound();
}
}
}
边栏推荐
猜你喜欢
二叉搜索树(基操篇)
A tour of gRPC:03 - proto序列化/反序列化
掌握这个提升路径,面试资料分享
The process of creating custom controls in QT to encapsulating them into toolbars (II): encapsulating custom controls into toolbars
Master this promotion path and share interview materials
Opencv personal notes
node:504报错
全网“追杀”钟薛高
Personal notes of graphics (2)
Opencv configuration 2019vs
随机推荐
二叉搜索树(基操篇)
字节跳动Android金三银四解析,android面试题app
The difference and working principle between compiler and interpreter
os、sys、random标准库主要功能
Lowcode: four ways to help transportation companies enhance supply chain management
Binary search tree (features)
LeetCode 1186. 删除一次得到子数组最大和 每日一题
网关Gateway的介绍与使用
LeetCode-SQL第一天
Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
Vs2019 configuration matrix library eigen
LeetCode 1986. The minimum working time to complete the task is one question per day
【图像传感器】相关双采样CDS
如何选择合适的自动化测试工具?
LeetCode 1043. 分隔数组以得到最大和 每日一题
Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
Arduino 控制的双足机器人
Master this promotion path and share interview materials
01tire+ chain forward star +dfs+ greedy exercise one
OpenGL personal notes