当前位置:网站首页>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();
}
}
}
边栏推荐
- Opencv configuration 2019vs
- Three. JS series (1): API structure diagram-1
- LeetCode 1654. 到家的最少跳跃次数 每日一题
- 【DesignMode】模板方法模式(Template method pattern)
- LeetCode 1049. 最后一块石头的重量 II 每日一题
- LeetCode 1626. The best team without contradiction
- Record the migration process of a project
- 最新Android高级面试题汇总,Android面试题及答案
- Temperature sensor chip used in temperature detector
- LeetCode 1986. The minimum working time to complete the task is one question per day
猜你喜欢
3000 words speak through HTTP cache
QML beginner
Pychart ide Download
最新阿里P7技术体系,妈妈再也不用担心我找工作了
【DesignMode】外观模式 (facade patterns)
二叉搜索树(基操篇)
Imitate the choice of enterprise wechat conference room
Horizontal and vertical centering method and compatibility
Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
QML初学
随机推荐
字节跳动Android面试,知识点总结+面试题解析
null == undefined
LeetCode 1049. Weight of the last stone II daily question
ByteDance Android gold, silver and four analysis, Android interview question app
运算符
水平垂直居中 方法 和兼容
爬虫(17) - 面试(2) | 爬虫面试题库
两类更新丢失及解决办法
网关Gateway的介绍与使用
LeetCode 312. 戳气球 每日一题
最新高频Android面试题目分享,带你一起探究Android事件分发机制
LeetCode 152. 乘积最大子数组 每日一题
Process from creation to encapsulation of custom controls in QT to toolbar (I): creation of custom controls
The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit
Prediction - Grey Prediction
Tidb cannot start after modifying the configuration file
第九届 蓝桥杯 决赛 交换次数
【DesignMode】外观模式 (facade patterns)
time标准库
Opencv personal notes