Magicodes.IE.ASPNETCore之多樣化介面使用

HueiFeng發表於2021-04-22

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();
        }
    });
})

相關文章