1. 程式人生 > 實用技巧 >Web API返回自定義資料給客戶端

Web API返回自定義資料給客戶端

服務端出現異常時,返回給客戶端status仍然是ok的。因此在前端的catch或是error是得到不到服務端的throw異常資訊的。

所以,你在服務端中,把異常時,也得作為成功執行返回給客戶端。


你可以寫一個類別:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Insus.NET.APIs
{
    public class Response
    {
        public bool ResponseStatus { get; set
; } public string Message { get; set; } public object ResponseData { get; set; } public Response() { } public Response(bool status, string message, object data) { ResponseStatus = status; Message = message; ResponseData = data; } } }
Source Code

Web API實現資料返回給客戶端。

 [HttpPost]
        public async Task<IHttpActionResult> GenerateQrCode(JObject jObj)
        {   

            Response response;

            try
            {
                //WriteFile(qr, out f);

                BarCode bc = new BarCode()
                {
                    BackgroundColor 
= jsonParams.BackgroundColor, ForegroundColor = jsonParams.ForegroundColor, Width = jsonParams.Width, Height = jsonParams.Height, Content = jsonParams.Content, FileName = f, MineType = "image/png" }; response = new Response(); response.ResponseStatus = true; var list = new List<BarCode>() { bc }; response.ResponseData = list.FirstOrDefault<BarCode>(); } catch (Exception ex) { response = new Response() { ResponseStatus = false, Message = ex.Message }; } return await Task.FromResult(Ok(response)); }
Source Code

前端angularjs呼叫api:

 $http({
                method: 'POST',
                url: '/api/IoSvc/GenerateQrCode',
                dataType: 'json',
                headers: {
                    'Content-Type': 'application/json; charset=utf-8'
                },
                data: JSON.stringify(arg),
            })
                .then(
                    function (response) {
                        var d = response.data
                        if (d.ResponseStatus) {
                            $scope.noImageHide = false;

                            $scope.FileName = d.ResponseData.FileName;
                        }
                        else {      
                            $scope.noImageHide = true;
                            $scope.FileName = "";
                            $window.alert(d.Message);
                        }
                    },
                    function (response) {
                        $window.alert(response.data);
                    }
                )
                .catch(function (response) {
                    $window.alert("catch:" + response.data);
                })
                //.finally(function () {
                //    console.log("Task Finished.");
                //})
                ;
Source Code