具有基本授权标头的MVC5和Swashbuckle(.NET 4.6.1框架)

时间:2017-05-01 05:25:08

标签: c# .net asp.net-mvc-5 swashbuckle .net-4.6.1

您好我使用Swashbuckle和MVC5,我能够生成Swagger UI,但我还需要基本授权标题。

我尝试过以下代码

public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        var isAuthorized = filterPipeline
                                         .Select(filterInfo => filterInfo.Instance)
                                         .Any(filter => filter is IAuthorizationFilter);

        var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (isAuthorized && !allowAnonymous)
        {
            operation.parameters.Add(new Parameter {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"                    
            });
        }
    }
}

并在web.config中添加以下内容

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
        <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
           <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
        </dependentAssembly>
    </assemblyBinding>
</runtime>

获取错误无法加载System.Web.Http 4.0.0

1 个答案:

答案 0 :(得分:1)

我怀疑招摇是否支持这一点,我遇到了这个https://github.com/swagger-api/swagger-ui/issues/1566,其中报告了带有昂首阔步问题的基本认证,但没有得到解决。

我建议使用Rest-client(Advance Rest客户端或postteman等)工具测试您的代码。