C#/.NET 分布式专题(SOA【面向服务】WebApi的使用)

.NET MVC/.NET COER 下WebApi基本使用如下

//[RoutePrefix("api/Values/")]//action就可以去掉这一节;如果某个方法又不要了,可以在路由前面加个~  [Route("~api/Values/{id:int}")]
public class ValuesController : ApiController
{
     
    // GET api/values
    [HttpGet]
    public IEnumerable<string> LGet()
    {
     
        return new string[] {
      "value1", "value2" };
    }

    // GET api/values/5
    [Route("api/Values/{id:int}")]//regex()
    [HttpGet]
    public string GetById(int id)//Id查询
    {
     
        return "value";
    }

    //[Route("api/Values/{id:int=10}")]//可空
    //[Route("api/Values/{id:int?}")]//可空
    //public string GetId(int id = 10)//Id查询
    //{
     
    //    return "value";
    //}

    /// 
    /// get value--value有子表数据--
    /// 
    /// 
    /// 
    [Route("api/Values/{id:int}/Type/{typeId:int}")]
    public string Get(int id, int typeId)//Id查询
    {
     
        return $"value-Type {id} {typeId}";
    }

    [Route("api/Values/{name}")]
    public string Get(string name)//名称查询
    {
     
        return $"value {name}";
    }

    [Route("api/Values/{id}/V2")]
    [HttpGet]
    public string LGetV333455(int id)
    {
     
        return "value V2";
    }

    // POST api/values
    public void Post([FromBody]string value)
    {
     
    }

    // PUT api/values/5
    public void Put(int id, [FromBody]string value)
    {
     
    }

    // DELETE api/values/5
    public void Delete(int id)
    {
     
    }
}

##WebApi 加入unity容器IOC, DI注入详解

使用

public class IOCController : ApiController
{
     
    private IUserService _UserService = null;
    public IOCController(IUserService userService)
    {
     
        this._UserService = userService;
    }

    public string Get(int id)
    {
     
        //IUserService service = new UserService();
        //IUserService service = ContainerFactory.BuildContainer().Resolve();
        return Newtonsoft.Json.JsonConvert.SerializeObject(this._UserService.Query(id));
    }
}

DI注入相关类

public class UnityDependencyResolver : IDependencyResolver
{
     
    private IUnityContainer _UnityContainer = null;
    public UnityDependencyResolver(IUnityContainer container)
    {
     
        _UnityContainer = container;
    }

    public IDependencyScope BeginScope()//Scope
    {
     
        return new UnityDependencyResolver(this._UnityContainer.CreateChildContainer());
    }

    public void Dispose()
    {
     
        this._UnityContainer.Dispose();
    }

    public object GetService(Type serviceType)
    {
     
        try
        {
     
            return ContainerFactory.BuildContainer().Resolve(serviceType);
        }
        catch (Exception ex)
        {
     
            Console.WriteLine(ex.Message);
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
     
        try
        {
     
            return ContainerFactory.BuildContainer().ResolveAll(serviceType);
        }
        catch (Exception ex)
        {
     
            Console.WriteLine(ex.Message);
            return null;
        }
    }
}
/// 
/// 需要在nuget引用之后,单独引用Unity.Configuration
/// 如果有AOP扩展,还需要引用Unity.Interception.Configuration
/// 因为我们是用配置文件来做的配置
/// 
public class ContainerFactory
{
     
    public static IUnityContainer BuildContainer()
    {
     
        //get
        //{
     
        return _Container;
        //}
    }

    private static IUnityContainer _Container = null;
    static ContainerFactory()
    {
     
        ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
        fileMap.ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "CfgFiles\\Unity.Config");//找配置文件的路径
        Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
        _Container = new UnityContainer();
        section.Configure(_Container, "WebApiContainer");
    }
}
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
  </configSections>
  <unity>
    <sectionExtension type="Microsoft.Practices.Unity.InterceptionExtension.Configuration.InterceptionConfigurationExtension, Unity.Interception.Configuration"/>
    <containers>
      <container name="WebApiContainer">
        <extension type="Interception"/>
        <register type="Ruanmou.SOA.Interface.IUserService,Ruanmou.SOA.Interface" mapTo="Ruanmou.SOA.Service.UserService, Ruanmou.SOA.Service">
          <!--
          <interceptor type="InterfaceInterceptor"/>
          <interceptionBehavior type="Ruanmou.Framework.AOP.LogBeforeBehavior, Ruanmou.Framework"/>
          <interceptionBehavior type="Ruanmou.Framework.AOP.LogAfterBehavior, Ruanmou.Framework"/>
          <interceptionBehavior type="Ruanmou.Framework.AOP.ParameterCheckBehavior, Ruanmou.Framework"/>
          <lifetime type="transient" />-->
        </register>
      </container>
    </containers>
  </unity>
</configuration>

路由注入

public static class WebApiConfig
{
     
    public static void Register(HttpConfiguration config)
    {
     
        // Web API 配置和服务
        config.DependencyResolver = new UnityDependencyResolver(ContainerFactory.BuildContainer());

        // Web API 路由
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",//默认的api路由
            routeTemplate: "api/{controller}/{id}",//正则规则,以api开头,第二个是控制器  第三个是参数
            defaults: new {
      id = RouteParameter.Optional }
        );

        //   config.Routes.MapHttpRoute(
        //    name: "CustomApi",//默认的api路由
        //    routeTemplate: "api/{controller}/{action}/{id}",//正则规则,以api开头,第二个是控制器  第三个是参数
        //    defaults: new { id = RouteParameter.Optional }
        //);
    }
}

你可能感兴趣的:(.Net通用工具)