11#: sdk Microsoft . NET. Sdk. Web
2+ // 解析参数:根目录和端口
3+ var baseDir = Directory . GetCurrentDirectory ( ) ;
4+ var root = args . Length > 0 && ! string . IsNullOrWhiteSpace ( args [ 0 ] )
5+ ? Path . GetFullPath ( args [ 0 ] )
6+ : Path . Combine ( baseDir , "WebSite" ) ;
27
3- using Microsoft . Extensions . FileProviders ;
4- var argsList = args ?? Array . Empty < string > ( ) ;
8+ var port = args . Length > 1 && int . TryParse ( args [ 1 ] , out var p ) ? p : 5200 ;
59
6- // 1. 解析根目录参数
7- string rootArg = argsList . Length > 0 && ! string . IsNullOrWhiteSpace ( argsList [ 0 ] )
8- ? argsList [ 0 ]
9- : string . Empty ;
10-
11- string baseDir = Directory . GetCurrentDirectory ( ) ;
12- string defaultWebRoot = Path . Combine ( baseDir , "WebSite" ) ;
13-
14- string root = ! string . IsNullOrEmpty ( rootArg )
15- ? rootArg
16- : ( Directory . Exists ( defaultWebRoot ) ? defaultWebRoot : baseDir ) ;
17-
18- if ( ! Path . IsPathRooted ( root ) )
19- {
20- root = Path . GetFullPath ( Path . Combine ( baseDir , root ) ) ;
21- }
22-
23- int port = 5200 ;
24- if ( argsList . Length > 1 && int . TryParse ( argsList [ 1 ] , out var p ) && p > 0 && p <= 65535 )
25- {
26- port = p ;
27- }
10+ // 创建并配置应用
2811var builder = WebApplication . CreateBuilder ( new WebApplicationOptions
2912{
3013 Args = args ,
3114 ContentRootPath = root ,
3215 WebRootPath = root
3316} ) ;
3417
35- builder . WebHost . ConfigureKestrel ( options =>
36- {
37- options . ListenLocalhost ( port ) ;
38- } ) ;
18+ builder . WebHost . UseUrls ( $ "http://localhost:{ port } ") ;
19+
3920var app = builder . Build ( ) ;
40- app . UseStaticFiles ( new StaticFileOptions
41- {
42- FileProvider = new PhysicalFileProvider ( root ) ,
43- RequestPath = "" ,
44- } ) ;
21+ app . UseStaticFiles ( ) ;
4522app . MapFallbackToFile ( "index.html" ) ;
4623
47- await app . RunAsync ( ) ;
24+ await app . RunAsync ( ) ;
0 commit comments