简体   繁体   中英

.NET CORE route Api sub domain to Api controller

I have Api Controllers and MVC controllers in my . NET CORE application.

How can I route sub domain api.mysite.com to point only on Api controllers, and dashboard.mysite.com to point on Web Application all in same project?

If you want to implement this in a single ASP.NET Core application, you can do something like this:

  1. Make Api controllers available say at path /Api . You can achieve this using routes, areas or application branches .

  2. Use a reverse proxy which is capable of URL rewriting (eg IIS on Win, Nginx on Linux). Configure the reverse proxy so that the requests arriving at api.mysite.com/path are forwarded to your application as /Api/path .

A remark: If you want to generate URLs in your Api controllers, you should remove the /Api prefix from the path to get correct URLs (and of course you have to configure your reverse proxy to append the necessary headers like X-Forwarded-Host , etc.) For this purpose you can use this simple middleware .

Update

As it was discussed in the comments, an application branch seems the best solution in this case because it enables separate pipelines for the MVC and API application parts.

Actually, it's very easy to define branches. All you need to do is to put a Map call at the beginning of your main pipeline in the Configure method of your Startup class:

public void Configure(IApplicationBuilder app)
{
    app.Map("/Api", BuildApiBranch);

    // middlewares for the mvc app, e.g.
    app.UseStaticFiles();

    // some other middlewares maybe...

    app.UseMvc(...);
}

private static void BuildApiBranch(IApplicationBuilder app)
{        
    // middlewares for the web api...

    app.UseMvc(...);
}

Now, when a request arrives and its path starts with /Api , the request gets "deflected" and goes through the branch pipeline (defined in BuildApiBranch method) instead of going through the main pipeline (defined in Configure method, following the Map call).

Some things to keep in mind:

  • When a request is "captured" by the branch, the prefix /Api is removed from the HttpContext.Request.Path property (and appended to HttpContext.Request.PathBase ). So you need to define the API routes in the UseMvc method as if the request path had no prefix at all .

  • Using this code you have two separate pipelines but they share the components registered in Startup.ConfigureServices . If this is undesired, it's possible to create separate DI containers for each of the pipelines. However, this is a somewhat advanced topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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