简体   繁体   English

ASP.NET Web Api 2.0中的Owin自定义路由MIddleware

[英]Owin Custom Routing MIddleware in ASP.NET Web Api 2.0

I have started building an ASP.NET Web API 2.0 application using the OWIN Middleware from Microsoft ( http://owin.org/ ). 我已经开始使用Microsoft的OWIN中间件来构建ASP.NET Web API 2.0应用程序( http://owin.org/ )。 I have several questions related to routing as I can't find a great tutorial on it for Web API. 我有几个与路由相关的问题,因为找不到适用于Web API的出色教程。 We have customers that could potentially have several companies (databases, essentially) that they want to service through this Web API. 我们有一些潜在客户,他们可能希望通过此Web API为多家公司(数据库)提供服务。 We wanted the user to be able to specify their company through a custom route. 我们希望用户能够通过自定义路线指定他们的公司。 For example, a route like so api/MyCompany/Products will load all of the products for MyCompany. 例如,类似api / MyCompany / Products之类的路由将加载MyCompany的所有产品。 Obviously, we do not want to pass the company name into every action on every controller, so I want to create a custom route or custom routing middleware if standard routing won't work. 显然,我们不想将公司名称传递到每个控制器的每个操作中,因此,如果标准路由不起作用,我想创建一个自定义路由或自定义路由中间件。

1) Are there any good tutorials on routing for Web API that I can look into to help me understand what I am doing and how I should be doing things? 1)我可以参考任何有关Web API路由的优秀教程来帮助我了解自己在做什么以及应该如何做吗?

2) Are there any good tutorials for building Middleware over OWIN for routing? 2)是否有通过OWIN构建用于路由的中间件的良好教程? Any in general? 一般吗?

3) Recommendations on a better way to do this, if there is one. 3)推荐一种更好的方法(如果有)。

The companies are necessary because we don't want to hard code anything into a web.config file. 公司是必要的,因为我们不想将任何内容硬编码到web.config文件中。 Basically, the app will have info on all of the companies and, using the route, will get metadata such as the related connection string. 基本上,该应用程序将包含所有公司的信息,并使用该路由获取元数据,例如相关的连接字符串。

Any advice will be great! 任何建议都会很棒! I know this probably isn't the usual post but I had no idea where to look. 我知道这可能不是通常的帖子,但我不知道在哪里看。 I haven't found anything of use via standard means (google and MSDN) unless I am just overlooking a simple concept. 除非我只是忽略了一个简单的概念,否则我还没有找到通过标准方式(谷歌和MSDN)使用的任何东西。

Have you tried looking into Attribute Routing in ASP.NET Web API 2 您是否尝试过研究ASP.NET Web API 2中的属性路由

which would allow you to set a route prefix on your controller to satisfy what you are looking for. 这将允许您在控制器上设置路由前缀以满足您的需求。

[RoutePrefix("api/{companyName}")]
public class CustomerController : ApiController {
    // GET api/MyCompany/products
    [Route("products")]
    public IEnumerable<Product> GetProducts(string companyName) { ... }

    // GET api/MyCompany/orders
    [Route("orders")]
    public IEnumerable<Order> GetOrders(string companyName) { ... }

    ....
}

if you read through the mentioned link you will see how to set it up and use it as needed. 如果您通读了所提到的链接,您将了解如何设置它并根据需要使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM