asp.net framework配置swagger并支持上传文件


c#写webapi时刚开始习惯用postman进行调试,但是感觉每次都要修改网址有点麻烦,后来发现swagger可以很好的解决这个问题,以下记录探索过程

1.swagger配置

  1. 安装nuget包Swashbuckle
    安装后会自动在App_Start生成SwaggerConfig.cs文件
  2. 项目右键——属性——生成,勾选生成xml文件
    eg bin\WebApi.xml
    【若对api写了注释,并在swagger中 开启了,则会自动生成一些说明节点】
  3. 添加注释配置
1)Register函数中取消 c.IncludeXmlComments(GetXmlCommentsPath()); 的注释
(2)添加函数
/// <summary>
///  添加XML解析,项目右键属性-生成勾选生成xml文档,对应的xml文件名和路径
 /// </summary>
 /// <returns></returns>
 private static string GetXmlCommentsPath()
 {
     return string.Format("{0}/bin/WebApi.xml", System.AppDomain.CurrentDomain.BaseDirectory);
 }

4.配置调试url
直接点击调试,在网址后加上swagger会进入如下页面:
在这里插入图片描述
复制上述网址,项目右键——属性——web,选择启动url,设置为上述网址,这样就可以避免每次都手动改网址了
在这里插入图片描述

2.配置swagger支持文件上传

(1)增加文件上传扩展和标签设置

/// <summary>
/// Swagger文件上传特性标注
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public sealed class SwaggerFormAttribute : Attribute
{
    /// <summary>
    /// Swagger特性标注
    /// </summary>
    /// <param name="name"></param>
    /// <param name="description"></param>
    public SwaggerFormAttribute(string name, string description)
    {
        Name = name;
        Description = description;
    }
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; private set; }
    /// <summary>
    /// 描述
    /// </summary>
    public string Description { get; private set; }
}
/// <summary>
/// 文件上传操作
/// </summary>
public class FileUploadOperation : IOperationFilter
{
    /// <summary>
    /// 运用
    /// </summary>
    /// <param name="operation"></param>
    /// <param name="schemaRegistry"></param>
    /// <param name="apiDescription"></param>
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        if (operation.parameters == null)
        {
            operation.parameters = new List<Parameter>();
        }
        var requestAttributes = apiDescription.GetControllerAndActionAttributes<SwaggerFormAttribute>();
        foreach (var attr in requestAttributes)
        {
            operation.parameters.Add(new Parameter
            {
                description = attr.Description,
                name = attr.Name,
                @in = "formData",
                required = true,
                type = "file",
            });
            operation.consumes.Add("multipart/form-data");
        }
    }
}

(2)增加文件上传配置

取消SwaggerConfig中c.OperationFilter<AssignOAuth2SecurityRequirements>();的注释
 改为c.OperationFilter<FileUploadOperation>();

(3)需要进行文件上传的函数增加特性标注

[HttpPost,SwaggerForm("文件", "选择zip压缩文件")]
public void FileUpload()
{
    HttpFileCollection fileCollection = HttpContext.Current.Request.Files;
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_Data\\Templates");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }
    string filepath = "";
    try
    {
        if (fileCollection.Count > 0)
        {
            HttpPostedFile file = fileCollection[0];//file.ContentLength文件长度
            filepath = path + file.FileName;
            //将上传的文件保存到App_Data
            file.SaveAs(path + file.FileName);
        }
    }
    catch(Exception ex)
    {
    }
    finally
    {
        
    }
}

(4)打开网页后会发现该接口已经支持文件上传了
在这里插入图片描述
(5)ps:若发现选择文件后直接退出了调试,修改如下设置即可:

在这里插入图片描述

413.1错误:请求筛选模块被配置为拒绝超过请求内容长度的请求。

在根目录下的Web.config
在根目录下的Web.config中增加允许上传文件配置:

 <system.webServer>
	<!--允许上传文件长度,单位字节,默认30m-->
	<security>
		<requestFiltering>
			<requestLimits maxAllowedContentLength="2147483648"/>
		</requestFiltering>
	</security>
  </system.webServer>

HttpContext.Current.Request.Files超过了最大请求长度

在根目录下的Web.config中增加最大请求长度配置:

<system.web>
    <!--最大请求长度,单位为kb-->
    <httpRuntime targetFramework="4.8" maxRequestLength="2147483647" executionTimeout="3600" />
  </system.web>

注意:maxRequestLength与maxAllowedContentLength的区别
a、前者表示请求长度,后者表示上传文件的大小;
b、前者单位kb,后者单位字节;
c、前者默认值4M,后者默认值30000000B,约30M;
d、两者的最大值都为2G

参考链接:https://www.jb51.net/article/88698.htm

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShirmyMao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值