Override host of webapi odata links

后端 未结 6 1753
Happy的楠姐
Happy的楠姐 2020-12-06 19:55

I\'m using WebAPI 2.2 and Microsoft.AspNet.OData 5.7.0 to create an OData service that supports paging.

When hosted in the production environment, the WebAPI lives o

6条回答
  •  旧时难觅i
    2020-12-06 20:38

    There is another solution, but it overrides url for the entire context. What I'd like to suggest is:

    1. Create owin middleware and override Host and Scheme properties inside
    2. Register the middleware as the first one

    Here is an example of middleware

    public class RewriteUrlMiddleware : OwinMiddleware
    {
        public RewriteUrlMiddleware(OwinMiddleware next)
            : base(next)
        {
        }
    
        public override async Task Invoke(IOwinContext context)
        {
            context.Request.Host = new HostString(Settings.Default.ProxyHost);
            context.Request.Scheme = Settings.Default.ProxyScheme;
            await Next.Invoke(context);
        }
    }
    

    ProxyHost is the host you want to have. Example: test.com

    ProxyScheme is the scheme you want: Example: https

    Example of middleware registration

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Use(typeof(RewriteUrlMiddleware));
            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);
        }
    }
    

提交回复
热议问题