.NET WebApi参数绑定的可选参数

时间:2019-06-21 19:38:56

标签: c# asp.net-web-api parameterbinding

我有一个内置于.NET WebApi的REST API。我创建了一个自定义参数绑定属性,用于从HTTP标头中提取值。在某些情况下,请求中可能存在或可能不存在标头,因此我希望能够执行以下操作将标头作为可选参数。

public IHttpActionResult Register([FromBody] RegistrationRequest request, [FromHeaderAuthorization] string authorization = null)
{

当我调用包含授权头的端点时,此方法工作正常。  当调用没有标题的端点时,却收到以下错误消息:

The request is invalid.', MessageDetail='The parameters dictionary does not contain an entry for parameter 'authorization' of type 'System.String'

我一直在尝试尝试确定是否可以通过这种方式将参数视为可选参数,并且发现了一些混合结果。看来在C#8.0中,我可以使用可为空的引用类型来实现此目的,但是Visual Studio指出8.0当前处于预览状态,因此对我而言并不是一个选择。  就是说,我还没有真正找到能够表明这种事情是否可行的其他东西。

我的问题是,是否有可能将此标头参数视为可选参数,或者我需要以其他方式进行处理?

1 个答案:

答案 0 :(得分:0)

我最终放弃了header参数,并朝着稍微不同的方向前进。

我已经创建了一个类来扩展HttpRequestMessage以执行诸如获取调用端点的客户端IP之类的事情,最后我添加了一种方法来处理头文件是否存在的检查,并根据需要检索必要的身份信息。

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    /* Method body excluded as irrelevant */
    public static string GetClientIpAddress(this HttpRequestMessage request) { ... }

    /** Added this method for handling the authorization header. **/
    public static Dictionary<string, string> HandleAuthorizationHeader(this HttpRequestMessage request)
    {
        Tenant tenant = new Tenant();
        IEnumerable<string> values;
        request.Headers.TryGetValues("Authorization", out values);
        string tenantConfig = ConfigurationUtility.GetConfigurationValue("tenantConfig");

        if (null != values)
        {
            // perform actions on authorization header.
        }
        else if(!string.IsNullOrEmpty(tenantConfig))
        {
            // retrieve the tenant info based on configuration.
        }
        else
        {
            throw new ArgumentException("Invalid request");
        }

        return tenant;
    }
}
相关问题