如何强制CreatedAtRoute生成位置从https开始?

时间:2017-04-10 10:39:48

标签: asp.net-core-webapi

我向我的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", ... }

但是位置标题中的网址应该是https。

传入请求命中均衡器,即https,然后请求为http。

1 个答案:

答案 0 :(得分:0)

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

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)为动作结果创建新类。此外,您还需要实现自己的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;
    }
}