【问题标题】:How to force CreatedAtRoute generate location started from https?如何强制 CreatedAtRoute 生成从 https 开始的位置?
【发布时间】:2017-04-11 17:07:28
【问题描述】:

我做 POST 到我的 api

curl -X POST --header 'Content-Type: application/json' 
--header 'Accept: application/json' 
--header 'Authorization: Bearer some_token' -d '{ some_data }'
'https://here_is_url'

作为回应,我得到了

{ ... "location": "http://here_is_right_url_except_http", "status": "201", ... }

但位置标头中的 url 应该带有 https。

传入的请求到达 https 的平衡器,然后请求以 http 的形式发送。

【问题讨论】:

    标签: asp.net-core-webapi


    【解决方案1】:

    找到两种方法来解决这个问题。

    1) 覆盖 UrlHelper

    public class HttpsUrlHelper : UrlHelper {
             public HttpsUrlHelper(ActionContext actionContext)
        : base(actionContext) {
    }
    
    protected override string GenerateUrl(string protocol, string host, VirtualPathData pathData, string fragment) {
            return base.GenerateUrl("https", host, pathData, fragment);
        }
    }
    
    public class ForcedHttpsUrlHelperFactory : IUrlHelperFactory {
        public IUrlHelper GetUrlHelper(ActionContext context) {
            return new HttpsUrlHelper(context);
        }
    }
    

    需要在Startup.cs中注册

    services.AddSingleton<IUrlHelperFactory, ForcedHttpsUrlHelperFactory>();
    

    2) 为动作 Result 创建新类。您还需要实现自己的 CreatedAtRoute 函数,该函数将返回 HttpsCreatedAtRouteResult 的实例。

    public class HttpsCreatedAtRouteResult : CreatedAtRouteResult {
        public HttpsCreatedAtRouteResult(object routeValues, object value)
            : base(routeValues, value) {
        }
    
        public HttpsCreatedAtRouteResult(string routeName, object routeValues, object value)
            : base(routeName, routeValues, value) {
        }
    
        public override void OnFormatting(ActionContext context) {
            base.OnFormatting(context);
            var url = context.HttpContext.Response.Headers[HeaderNames.Location];
    
            // do with url whatever you need
    
            context.HttpContext.Response.Headers[HeaderNames.Location] = url;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-05
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      • 1970-01-01
      相关资源
      最近更新 更多