Magicodes.IE.ASPNETCore之多樣化接口使用

1.安裝包

Install-Package Magicodes.IE.AspNetCore

2.開始配置

Startup.cs的Configure()方法中,在UseRouting()中間件之後,註冊如下中間件

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseMagiCodesIE();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

上面這種以中間件形式可以爲我們提供導出服務,那麼我們再看一下另一種方式如下所示:

  public void ConfigureServices(IServiceCollection services)
            {
                services.AddControllers(options=>options.Filters.Add(typeof(MagicodesFilter)));
            }

上面兩種方式都可以爲我們提供導出服務,我們只需要對我們的控制器進行配置我們的特性,在這邊呢 特性主要做的是一個標識作用,標識他的一些相關的內容數據,同時標識他可以當成文件導出。

[HttpGet("excel")]
[Magicodes(Type = typeof(ExportTestDataWithAttrs))]
public List<ExportTestDataWithAttrs> Excel()
{
    return GenFu.GenFu.ListOf<ExportTestDataWithAttrs>(100);
}

上面代碼片段中我們標識這個類允許被導出。同時我們需要通過Type指定我們被導出類的類型。

這樣填寫完後我們可以通過對該地址的調用,但是注意我們必須要添加請求頭以標識被導出的文件類型。如果不添加請求頭,那麼此處將返回的還是json格式的數據。請求頭名稱爲Magicodes-Type

       /// <summary>
        ///     XLSX
        /// </summary>
        internal const string XLSXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        /// <summary>
        ///     PDF
        /// </summary>
        internal const string PDFHttpContentMediaType = "application/pdf";
        /// <summary>
        ///     DOCX
        /// </summary>
        internal const string DOCXHttpContentMediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        /// <summary>
        ///     HTML
        /// </summary>
        internal const string HTMLHttpContentMediaType = "text/html";

如果說是模板導出word或者pdf甚至說html文件那麼我們也是同樣的操作如下所示:

[HttpGet("Word")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Word()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "張三",
                Payee = "湖南心萊信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "運動訓練",
                Remark = "學費",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "貳萬貳仟玖佰叄拾玖圓肆角叄分",
                Code = "19071800001"
            };
        }

我們還是需要對其指定Type,然後通過TemplatePath進行指定模板地址即可

同樣的我們還可以通過請求頭進行標識本次請求是否是文件格式導出。


        [HttpGet("pdf")]
        [Magicodes(Type = typeof(BatchPortraitReceiptInfoInput), TemplatePath = ".//ExportTemplates//batchReceipt.cshtml")]
        public BatchPortraitReceiptInfoInput Pdf()
        {

            var input = new BatchPortraitReceiptInfoInput
            {
                Payee = "湖南心萊信息科技有限公司",
                SealUrl =
                @"data:image/jpeg;base64....",
                LogoUrl =
                @"data:image/png;base64....",
                ReceiptInfoInputs = new List<BatchPortraitReceiptInfoDto>()
            };

            for (var i = 0; i < 500; i++)
                input.ReceiptInfoInputs.Add(new BatchPortraitReceiptInfoDto
                {
                    Amount = 22939.43M,
                    Grade = "2019秋",
                    IdNo = "43062619890622xxxx",
                    Name = "張三",
                    PaymentMethod = "微信支付",
                    Profession = "運動訓練",
                    Remark = "學費",
                    TradeStatus = "已完成",
                    TradeTime = DateTime.Now,
                    UppercaseAmount = "貳萬貳仟玖佰叄拾玖圓肆角叄分",
                    Code = "1907180000" + i
                });
            return input;
        }


        [HttpGet("Html")]
        [Magicodes(Type = typeof(ReceiptInfo), TemplatePath = ".//ExportTemplates//receipt.cshtml")]
        public ReceiptInfo Html()
        {
            return new ReceiptInfo
            {
                Amount = 22939.43M,
                Grade = "2019秋",
                IdNo = "43062619890622xxxx",
                Name = "張三",
                Payee = "湖南心萊信息科技有限公司",
                PaymentMethod = "微信支付",
                Profession = "運動訓練",
                Remark = "學費",
                TradeStatus = "已完成",
                TradeTime = DateTime.Now,
                UppercaseAmount = "貳萬貳仟玖佰叄拾玖圓肆角叄分",
                Code = "19071800001"
            };
        }

Swagger中使用

通過繼承IOperationFilter接口,創建AddRequiredHeaderParameter類,添加一個header類型的參數,並且Header Name爲Magicodes-Type如下所示:

    public class AddRequiredHeaderParameter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<OpenApiParameter>();
            }

            operation.Parameters.Add(new OpenApiParameter
            {
                Name = "Magicodes-Type",
                In = ParameterLocation.Header,
                Required = false,
                Description = "根據HttpContentMediaType添加指定的header值,導出不同格式的文件。"
            });
        }
    }

然後轉到ConfigureServices()方法中,在AddSwaggerGen方法中添加如下內容:

   c.OperationFilter<AddRequiredHeaderParameter>();

XMLHttpRequest使用

XMLHttpRequest的使用中,和正常導出來說幾乎一樣,不過需要額外注意以下幾個地方:

  • 修改responseType爲blob。
  • 添加Http Header。
  • 以及對二進制流的處理。
document.querySelector("#downloadexcel").onclick = function() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "https://localhost:5001/api/Magicodes/excel", true); //也可以使用Post
    xmlhttp.responseType = 'blob';
    xmlhttp.setRequestHeader("Magicodes-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    xmlhttp.send();
    // readyState == 4 爲請求完成,status == 200爲請求成功返回的狀態
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            var name = xmlhttp.getResponseHeader("Content-disposition");
            var filename = name.substring(20, name.length);
            var blob = new Blob([xmlhttp.response], {
                type: 'text/xlsx'
            });
            var Url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = Url;
            link.download = filename;
            link.click();
        }
    }
}

jQuery Ajax使用

對於jQuery AjaxXMLHttpRequest的注意事項是一致的。詳細可參考如下代碼示例,不過目前對於示例的演示只是針對於Excel導出的,關於其他格式的導出,可參考我們前面介紹的Magicodes-Type常量內容,當然對於其他文件的導出同樣也是對responseType、以及blob類型進行修改。

$("#downloadexcel").click(function() {
    $.ajax({
        url: "https://localhost:5001/api/Magicodes/excel",
        type: 'GET',
        headers: {
            'Magicodes-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        },
        xhrFields: {
            responseType: 'blob'
        },
        success: function(data, status, xhr) {
            var name = xhr.getResponseHeader("Content-disposition");
            var filename = name.substring(20, name.length);
            var blob = new Blob([data], {
                type: 'text/xlsx'
            });
            var Url = URL.createObjectURL(blob);
            var link = document.createElement('a');
            link.href = Url;
            link.download = filename;
            link.click();
        }
    });
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章