我已将Swashbuckle添加到新的.Net Core Web API中以启用Swagger文档。
真正挖掘提供的Try-It-Out选项。
但是,在调用任何下划线业务逻辑之前,库中是否有可以检查的东西?
例如。在删除端点上尝试一下。我想保持按钮完好无损并且正常工作,但是在使用swagger进行调用的情况下,我不想实际删除资源。
答案 0 :(得分:0)
我喜欢将Swagger UI完整保留的想法,但不是消费者能够随机提交任何类型数据的想法。
我决定创建一个处理案例的简单update()
。
与我原来的帖子一样,这个想法是允许按钮工作,但对于某些动词,实际上并没有对任何数据进行更改。
所以我的解决方案是:
自定义操作过滤器属性:
ActionFilterAttribute
在/// <summary>
/// Simple action filter to prevent executing the action for certain http methods
/// </summary>
public class SwaggerIgnore : ActionFilterAttribute
{
string[] _ignoreMethods;
/// <summary>
/// Ignores the request when coming from Swagger.
///
/// Will return a default OK result.
///
/// Handy if you want to allow the "try" button, but not allow changes to entities; such as HttpDelete
/// </summary>
/// <param name="ignoreMethods">List of methods to ignore; get, delete etc</param>
public SwaggerIgnore(string[] ignoreMethods)
{
_ignoreMethods = ignoreMethods.Select(s => s.ToLower()).ToArray();
}
public override void OnActionExecuting(ActionExecutingContext context)
{
string methodExecuting = context.HttpContext.Request.Method.ToLower();
string referrer = context.HttpContext.Request.Headers["Referer"].ToString().ToLower();
if (_ignoreMethods.Contains(methodExecuting) && referrer.Contains("swagger"))
context.Result = new OkResult();
else
base.OnActionExecuting(context);
}
}
文件中,设置如下:
Startup.cs
所以现在,当从swagger页面运行任何删除,发布或放置时,实际上没有处理任何数据,但是操作返回OK。
答案 1 :(得分:0)
另一种方法是使用允许更灵活的AuthorizeAttribute
,以防万一我们想要允许一些但不允许其他人。
public class IgnoreSwaggerUiRequestAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(HttpActionContext a)
{
bool methodNotAllowed = false;
try
{
methodNotAllowed = a.Request.Headers.Referrer.AbsoluteUri.Contains("swagger/ui");
}
catch { }
if (methodNotAllowed)
{
a.Response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.MethodNotAllowed,
Content = new StringContent("This method is not allowed from the swagger ui")
};
}
}
}
然后我们装饰那些我们不想显示任何数据的方法:
[IgnoreSwaggerUiRequest]
public string Delete(int id)