ASP.NET Core中为指定类添加WebApi服务功能
POCO控制器簡介
public class PocoController
{
? ?public IActionResult Index()
? ?{
? ? ? ?return new ContentResult() { Content = “Hello from POCO controller!” };
? ?}
}
[Controller]
public class Poco
{
? ?public IActionResult Index()
? ?{
? ? ? ?return new ContentResult() { Content = “Hello from POCO controller!” };
? ?}
}
POCO控制器原理
實現自定義判斷規則
internal class ServiceControllerFeatureProvider : IApplicationFeatureProvider<ControllerFeature>
{
? ?private const string ControllerTypeNameSuffix = "Controller";
? ?private readonly IEnumerable<Type> ServiceTypes;
? ?public ServiceControllerFeatureProvider(IEnumerable<Type> ServiceTypes)
? ?{
? ? ? ? ? ?this.ServiceTypes = ServiceTypes;
? ?}
? ?public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
? ?{
? ? ? ?foreach (var type in Reflection.CurrentAssembiles.SelectMany(o => o.DefinedTypes))
? ? ? ?{
? ? ? ? ? ?if (IsController(type) || ServiceTypes.Any(o => type.IsClass && o.IsAssignableFrom(type)) && !feature.Controllers.Contains(type))
? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?feature.Controllers.Add(type);
? ? ? ? ? ?}
? ? ? ?}
? ?}
? ?protected bool IsController(TypeInfo typeInfo)
? ?{
? ? ? ?//...
? ?}
}
public interface ITestService
{
? ?string Test(string name);
}
[Route("test")]
public class TestService : ITestService
{
? ?[Route("{name}"), HttpGet]
? ?public string Test(string name)
? ?{
? ? ? ?return "Hello " + name;
? ?}
}
配置自定義規則
//示例直接new ServiceCollection對象,下面有完整的能運行的示例代碼。
var services = new ServiceCollection();
services.AddMvcCore()
? ? ? ?.ConfigureApplicationPartManager(manager =>
? ? ? ?{
? ? ? ? ? ?var featureProvider = new ServiceControllerFeatureProvider(typeof(ITestService));
? ? ? ? ? ?manager.FeatureProviders.Add(featureProvider);
? ? ? ?});
看看效果
? ?<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.0.0" />
? ?<PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.0.0" />
internal class Program
{
? ?public static void Main(string[] args)
? ?{
? ? ? new WebHostBuilder()
? ? ? ? ? ?.UseKestrel()
? ? ? ? ? ?.UseUrls("http://localhost:8080")
? ? ? ? ? ?.ConfigureServices(services =>
? ? ? ? ? ?{
? ? ? ? ? ? ? ?services.AddMvcCore()
? ? ? ? ? ? ? ?.ConfigureApplicationPartManager(manager =>
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?var featureProvider = new ServiceControllerFeatureProvider(typeof(ITestService));
? ? ? ? ? ? ? ? ? ?manager.FeatureProviders.Add(featureProvider);
? ? ? ? ? ? ? ?});
? ? ? ? ? ?})
? ? ? ? ? ?.Configure(app => app.UseMvc())
? ? ? ? ? ?.Build()
? ? ? ? ? ?.Start();
? ?}
}
總結
總結
以上是生活随笔為你收集整理的ASP.NET Core中为指定类添加WebApi服务功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在Mac的Docker中运行DotNet
- 下一篇: asp.net ajax控件工具集 Au