4

I have a .NET Web API project. I was able to add Swagger by installing the Swashbuckle NuGet package. Swagger now makes a nice web page that provides documentation and ability to test by going to this url: http://localhost:20475/product-catalog-api/swagger/ui/index This part works great. However, when I add FluentValidation and set it up in the WebApiConfig.cs, all of the requests to my site get high-jacked and instead of seeing the Swagger html page, I only get a JSON with an empty response.

I used this article by Matthew Jones to set up FluentValidation: http://www.exceptionnotfound.net/custom-validation-in-asp-net-web-api-with-fluentvalidation/

Here is what my web api config looks like:

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services
    config.Filters.Add(new ValidateModelStateFilter());
    config.MessageHandlers.Add(new ResponseWrappingHandler());

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: Version + "/{action}",
        defaults: new {controller = "Main"}
    );

    FluentValidationModelValidatorProvider.Configure(config);
}

I could trigger the FluentValidation manually in every web service method, but I would like to have a generic solution like Matthew Jones did with the Filters and MessageHandlers. Basically what I want to do is say IF the request is for swagger-ui then do not route through FluentValidation.

4

1 回答 1

4

我最终在里面添加了这段代码ResponseWrappingHandler。可能有一种更优雅的方式,但这对我有用。这会导致 swagger 页面请求退出 FluentValidation 钩子。

if (request.RequestUri.AbsolutePath.Contains("swagger"))
{
    return response;
}
于 2016-03-21T21:06:30.957 回答