瀏覽代碼

修正并添加jwt认证代码

luocaiyang 3 年之前
父節點
當前提交
b6d48375d3
共有 43 個文件被更改,包括 420 次插入225 次删除
  1. 37 14
      wispro.sp.api/Controllers/AppealController.cs
  2. 4 2
      wispro.sp.api/Controllers/AttachFilesController.cs
  3. 3 1
      wispro.sp.api/Controllers/BasePointRuleController.cs
  4. 3 1
      wispro.sp.api/Controllers/CalMonthController.cs
  5. 1 1
      wispro.sp.api/Controllers/PerformanceItemController.cs
  6. 2 9
      wispro.sp.api/Controllers/StaffController.cs
  7. 1 1
      wispro.sp.api/Controllers/StaffGradeController.cs
  8. 1 1
      wispro.sp.api/Controllers/VerifyCoefficientController.cs
  9. 15 7
      wispro.sp.web/Auth/JwtAuthenticationStateProvider.cs
  10. 3 4
      wispro.sp.web/Components/CreateAppeal.razor
  11. 1 5
      wispro.sp.web/Components/CreateAppeal.razor.cs
  12. 8 4
      wispro.sp.web/Components/Radar.razor
  13. 0 1
      wispro.sp.web/Components/ReviewerAppeal.razor.cs
  14. 2 2
      wispro.sp.web/Components/RightContent.razor.cs
  15. 1 2
      wispro.sp.web/Components/StaffSelect.razor
  16. 4 1
      wispro.sp.web/Components/StaffSelect.razor.cs
  17. 1 1
      wispro.sp.web/Components/UserGradeSelect.razor
  18. 4 1
      wispro.sp.web/Components/UserGradeSelect.razor.cs
  19. 1 1
      wispro.sp.web/Layouts/LoginLayout.razor
  20. 12 2
      wispro.sp.web/Models/CreateAppealModel.cs
  21. 0 2
      wispro.sp.web/Models/ReviewerAppealModel.cs
  22. 8 2
      wispro.sp.web/Pages/AppCase/MyCaselist.razor
  23. 28 13
      wispro.sp.web/Pages/AppCase/MyCaselist.razor.cs
  24. 2 1
      wispro.sp.web/Pages/AppCase/MyFistPage.razor.cs
  25. 0 1
      wispro.sp.web/Pages/CustomerList.razor.cs
  26. 6 15
      wispro.sp.web/Pages/LoginPages.razor.cs
  27. 1 1
      wispro.sp.web/Pages/StaffGrade.razor
  28. 2 2
      wispro.sp.web/Pages/StaffGrade.razor.cs
  29. 0 1
      wispro.sp.web/Pages/StaffList.razor
  30. 0 2
      wispro.sp.web/Pages/UploadData.razor
  31. 4 1
      wispro.sp.web/Pages/Welcome.razor
  32. 36 25
      wispro.sp.web/Pages/Welcome.razor.cs
  33. 2 1
      wispro.sp.web/Program.cs
  34. 49 20
      wispro.sp.web/Services/AppealTypeService.cs
  35. 10 13
      wispro.sp.web/Services/AuthService.cs
  36. 4 6
      wispro.sp.web/Services/CalMonthServices.cs
  37. 110 0
      wispro.sp.web/Services/HttpService.cs
  38. 9 21
      wispro.sp.web/Services/PerformanceItemServices.cs
  39. 9 16
      wispro.sp.web/Services/StaffGradeService.cs
  40. 31 18
      wispro.sp.web/Services/UserService.cs
  41. 1 1
      wispro.sp.web/wispro.sp.web.csproj
  42. 3 1
      wispro.sp.web/wwwroot/appsettings.json
  43. 1 1
      wispro.sp.web/wwwroot/index.html

+ 37 - 14
wispro.sp.api/Controllers/AppealController.cs

@@ -1,4 +1,5 @@
-using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.EntityFrameworkCore;
 using System;
@@ -14,6 +15,7 @@ namespace wispro.sp.api.Controllers
 {
     [Route("api/[controller]/[action]")]
     [ApiController]
+    [Authorize]
     public class AppealController : ControllerBase
     {
         spDbContext Context;
@@ -44,13 +46,16 @@ namespace wispro.sp.api.Controllers
         /// <param name="reviewerId"></param>
         /// <param name="appealObject"></param>
         /// <returns></returns>
-        public IActionResult CreateAppeal(int ItemId, int typeid, int reviewerId, AppealObject appealObject)
+        public ApiSaveResponse CreateAppeal(int ItemId, int typeid, int reviewerId, AppealObject appealObject)
         {
+            ApiSaveResponse response = new ApiSaveResponse();
+            response.Success = true;
+
             AppealRecord appealRecord = new AppealRecord();
             appealRecord.ItemId = ItemId;
             appealRecord.TypeId = typeid;
             appealRecord.ReviewerId = reviewerId;
-            appealRecord.CreaterId = 11;// Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault().Id;
+            appealRecord.CreaterId =  Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault().Id;
             appealRecord.CreateTime = DateTime.Now;
 
             var t = Context.Database.BeginTransaction();
@@ -74,18 +79,22 @@ namespace wispro.sp.api.Controllers
                 Context.SaveChanges();
                 t.Commit();
 
-                return Ok();
+                return response;
             }
             catch (Exception ex)
             {
                 t.Rollback();
-
-                return BadRequest(ex.Message);
+                response.Success = true;
+                response.ErrorMessage = ex.Message;
+                return response;
             }
         }
 
-        public IActionResult ReviewerAppeal(int appealRecordId,AppealObject appealObject)
+        public ApiSaveResponse ReviewerAppeal(int appealRecordId,AppealObject appealObject)
         {
+            ApiSaveResponse response = new ApiSaveResponse();
+            response.Success = true;
+
             var appealRecord = Context.AppealRecords.Where<AppealRecord>(p => p.Id == appealRecordId).FirstOrDefault();
 
             if(appealRecord != null)
@@ -93,10 +102,9 @@ namespace wispro.sp.api.Controllers
                 var t = Context.Database.BeginTransaction();
                 try
                 {
-                    appealRecord.ReviewerId = 5;// Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault().Id;
+                    appealRecord.ReviewerId = Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault().Id;
                     appealRecord.State = 1;
                     appealRecord.ReviewTime = DateTime.Now;
-                    //Context.AppealRecords.Add(appealRecord);
 
                     Context.SaveChanges();
                     foreach (var fieldValue in appealObject.inputFieldValues)
@@ -105,7 +113,6 @@ namespace wispro.sp.api.Controllers
                         fieldValue.AppealRecordId = appealRecord.Id;
                     }
                     Context.InputFieldValues.AddRange(appealObject.inputFieldValues);
-                    //throw (new ApplicationException("输入不能为空"));
                     Context.SaveChanges();
                     if (appealObject.attachFiles != null)
                     {
@@ -132,18 +139,22 @@ namespace wispro.sp.api.Controllers
                     Context.SaveChanges();
                     t.Commit();
 
-                    return Ok();
+                    return response;
                 }
                 catch (Exception ex)
                 {
                     t.Rollback();
 
-                    return BadRequest(ex.Message);
+                    response.Success = true;
+                    response.ErrorMessage = ex.Message;
+                    return response;
                 }
             }
             else
             {
-                return BadRequest("申诉不存在!");
+                response.Success = true;
+                response.ErrorMessage = "申诉不存在!";
+                return response;
             }
             
         }
@@ -289,10 +300,22 @@ namespace wispro.sp.api.Controllers
         {
             var data = Context.AppealRecords.Where<AppealRecord>(ar => ar.CreaterId == userId || (ar.ReviewerId == userId && ar.State !=1));
 
-            return data.Include(p => p.Reviewer)
+            var retList = data.Include(p => p.Reviewer)
                 .Include(p => p.Creater)
                 .Include(p => p.Item)
                 .Include(p => p.Type).ToList();
+
+            foreach(var record in retList)
+            {
+                record.Creater.ItemStaffs = null;
+                record.Creater.ReviewerItems = null;
+                record.Creater.Customers = null;
+                record.Item.ItemStaffs = null;
+                record.Item.PreOastaff = null;
+                record.Item.Reviewer = null;
+            }
+
+            return retList;
             
         }
 

+ 4 - 2
wispro.sp.api/Controllers/AttachFilesController.cs

@@ -1,4 +1,5 @@
-using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Hosting;
 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using Microsoft.AspNetCore.StaticFiles;
@@ -16,6 +17,7 @@ namespace wispro.sp.api.Controllers
 {
     [Route("api/[controller]/[action]")]
     [ApiController]
+    [Authorize]
     public class AttachFilesController : ControllerBase
     {
         private readonly IWebHostEnvironment env;
@@ -120,7 +122,7 @@ namespace wispro.sp.api.Controllers
                 var untrustedFileName = file.FileName;
                 attachFile.Name  = untrustedFileName;
 
-                Staff uploadUser = Context.Staffs.Where<Staff>(s => s.Name == "何倚雯").FirstOrDefault();
+                Staff uploadUser = Context.Staffs.Where<Staff>(s => s.Name == User.Identity.Name).FirstOrDefault();
 
                 if (uploadUser != null)
                 {

+ 3 - 1
wispro.sp.api/Controllers/BasePointRuleController.cs

@@ -1,4 +1,5 @@
-using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
 using Microsoft.EntityFrameworkCore;
 using System;
 using System.Collections.Generic;
@@ -13,6 +14,7 @@ namespace wispro.sp.api.Controllers
 {
     [Route("api/[controller]/[action]")]
     [ApiController]
+    [Authorize]
     public class BasePointRuleController : ControllerBase
     {
         spDbContext Context;

+ 3 - 1
wispro.sp.api/Controllers/CalMonthController.cs

@@ -1,4 +1,5 @@
-using Microsoft.AspNetCore.Http;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using System;
 using System.Collections.Generic;
@@ -10,6 +11,7 @@ namespace wispro.sp.api.Controllers
 {
     [Route("api/[controller]/[action]")]
     [ApiController]
+    [Authorize]
     public class CalMonthController : ControllerBase
     {
         spDbContext Context;

+ 1 - 1
wispro.sp.api/Controllers/PerformanceItemController.cs

@@ -17,7 +17,7 @@ namespace wispro.sp.api.Controllers
 {
     [Route("api/[controller]/[action]")]
     [ApiController]
-    //[Authorize]
+    [Authorize]
     public class PerformanceItemController : ControllerBase
     {
         spDbContext Context;

+ 2 - 9
wispro.sp.api/Controllers/StaffController.cs

@@ -10,7 +10,7 @@ using Microsoft.AspNetCore.Authorization;
 
 namespace wispro.sp.api.Controllers
 {
-    //[Authorize]
+    [Authorize]
     [Route("api/[controller]/[action]")]
     [ApiController]
     public class StaffController : ControllerBase
@@ -36,14 +36,7 @@ namespace wispro.sp.api.Controllers
             ret.TotalCount = Context.Staffs.Count<Staff>();
 
             List<Staff> retList = Context.Staffs.Skip<Staff>((pageIndex - 1) * pageSize).Take(pageSize).ToList<Staff>();
-
-            //for(int i = (pageIndex-1) * pageSize; i < pageIndex  * pageSize; i++)
-            //{
-            //    if (i < CacheList.Count)
-            //    {
-            //        retList.Add(CacheList[i]);
-            //    }
-            //}
+            
             ret.Results = retList;
 
             return ret;

+ 1 - 1
wispro.sp.api/Controllers/StaffGradeController.cs

@@ -9,7 +9,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
 
 namespace wispro.sp.api.Controllers
 {
-    //[Authorize]
+    [Authorize]
     [Route("api/[controller]/[action]")]
     [ApiController]
     public class StaffGradeController : ControllerBase

+ 1 - 1
wispro.sp.api/Controllers/VerifyCoefficientController.cs

@@ -11,7 +11,7 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
 
 namespace wispro.sp.api.Controllers
 {
-    //[Authorize]
+    [Authorize]
     [Route("api/[controller]")]
     [ApiController]
     public class VerifyCoefficientController : ControllerBase

+ 15 - 7
wispro.sp.web/Auth/JwtAuthenticationStateProvider.cs

@@ -8,6 +8,7 @@ using System.Security.Claims;
 using System.Net.Http;
 
 using wispro.sp.web.Utils;
+using wispro.sp.share.webViewObject;
 
 namespace wispro.sp.web.Auth
 {
@@ -28,30 +29,37 @@ namespace wispro.sp.web.Auth
         public override async Task<AuthenticationState> GetAuthenticationStateAsync()
         {
             //確認localstorage裡面是否有token
-            string tokenInLocalStorage = await localStorageService.GetItemAsStringAsync("authToken");
-            if (string.IsNullOrEmpty(tokenInLocalStorage))
+            var tokenInLocalStorage = await localStorageService.GetItemAsync<userToken>("authToken");
+            
+            if (tokenInLocalStorage == null)
             {
+                Console.WriteLine($"Token:匿名!");
                 //沒有的話,回傳匿名使用者
-                return null;
+                return anonymous;
             }
-
             
             //將token取出轉為claim
-            var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);
-
+            var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage.Token);
+            Console.WriteLine($"Token:{tokenInLocalStorage.Token}");
             //在每次request的header中帶入bearer token
-            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage);
+            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", tokenInLocalStorage.Token);
 
             //回傳帶有user claim的AuthenticationState物件
             return new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt")));
         }
 
+
         public void NotifyUserAuthentication(string token)
         {
+            
             var claims = JwtParser.ParseClaimsFromJwt(token);
+            
             var authenticatedUser = new ClaimsPrincipal(new ClaimsIdentity(claims, "jwt"));
+            
             var authState = Task.FromResult(new AuthenticationState(authenticatedUser));
+            
             NotifyAuthenticationStateChanged(authState);
+            
         }
 
         public void NotifyUserLogOut()

+ 3 - 4
wispro.sp.web/Components/CreateAppeal.razor

@@ -1,7 +1,8 @@
 @inherits FeedbackComponent<CreateAppealModel>
 
 
-
+@if (_Model.Item.Id > 0)
+{
 <Card Style="width:100%" Bordered>
     <div>
         <Row>
@@ -18,10 +19,8 @@
         </Row>
     </div>
 </Card>
-@if (!string.IsNullOrEmpty(_ErrorMessage)) 
-{ 
-<Alert Message="@_ErrorMessage" Type="@AlertType.Error" />
 }
+
 <Card>
     <Form Model="@_Model" LabelColSpan="6" WrapperColSpan="16" Size="@AntSizeLDSType.Small">
         <FormItem Label="请谁确认">

+ 1 - 5
wispro.sp.web/Components/CreateAppeal.razor.cs

@@ -68,7 +68,6 @@ namespace wispro.sp.web.Components
         protected override async void OnInitialized()
         {
             _Model = base.Options ?? new CreateAppealModel();
-            //Console.WriteLine($"Success:{JsonSerializer.Serialize(_Model)}");
             base.OnInitialized();
             feedbackRef = base.FeedbackRef;
         }
@@ -89,9 +88,6 @@ namespace wispro.sp.web.Components
             //_ = feedbackRef.CloseAsync();
         }
 
-        //private void OnFinishFailed(EditContext editContext)
-        //{
-        //    Console.WriteLine($"Failed:{JsonSerializer.Serialize(Model)}");
-        //}
+        
     }
 }

+ 8 - 4
wispro.sp.web/Components/Radar.razor

@@ -20,10 +20,10 @@
 @inject IChartService ChartService
 @code
 { 
-    [Parameter] 
+    [Parameter]
     public bool HasLegend { get; set; } = false;
 
-    [Parameter] 
+    [Parameter]
     public int Height { get; set; } = 343;
 
     private IChartComponent _chart;
@@ -65,7 +65,11 @@
     protected override async System.Threading.Tasks.Task OnInitializedAsync()
     {
         await base.OnInitializedAsync();
-        var data = await ChartService.GetRadarDataAsync();
-        await _chart.ChangeData(data);
+        try
+        {
+            var data = await ChartService.GetRadarDataAsync();
+            await _chart.ChangeData(data);
+        }
+        catch { }
     }
 }

+ 0 - 1
wispro.sp.web/Components/ReviewerAppeal.razor.cs

@@ -28,7 +28,6 @@ namespace wispro.sp.web.Components
         protected override async void OnInitialized()
         {
             _Model = base.Options ?? new ReviewerAppealModel();
-            //Console.WriteLine($"Success:{JsonSerializer.Serialize(_Model)}");
             base.OnInitialized();
             feedbackRef = base.FeedbackRef;
         }

+ 2 - 2
wispro.sp.web/Components/RightContent.razor.cs

@@ -58,7 +58,7 @@ namespace wispro.sp.web.Components
         {
             await base.OnInitializedAsync();
             SetClassMap();
-            _currentUser = UserService.CurrentUser;
+            _currentUser = await UserService.GetUser();
             var notices = await ProjectService.GetNoticesAsync();
             _notifications = notices.Where(x => x.Type == "notification").Cast<NoticeIconData>().ToArray();
             _messages = notices.Where(x => x.Type == "message").Cast<NoticeIconData>().ToArray();
@@ -85,7 +85,7 @@ namespace wispro.sp.web.Components
                     break;
                 case "logout":
                     authorProvider.LogoutAsync();
-                    //NavigationManager.NavigateTo("/LoginPages");
+                    NavigationManager.NavigateTo("/LoginPages");
                     break;
             }
         }

+ 1 - 2
wispro.sp.web/Components/StaffSelect.razor

@@ -1,5 +1,4 @@
-@inject IUserService _UserService;
-
+
 <Select DataSource="@_ShowStaffs"
         DefaultValue="@StaffId"
         LabelName="@nameof(wispro.sp.entity.Staff.Name)"

+ 4 - 1
wispro.sp.web/Components/StaffSelect.razor.cs

@@ -4,7 +4,7 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using wispro.sp.entity;
-
+using wispro.sp.web.Services;
 
 namespace wispro.sp.web.Components
 {
@@ -21,6 +21,9 @@ namespace wispro.sp.web.Components
         [Parameter]
         public EventCallback<int?> StaffIdChanged { get; set; }
 
+        [Inject] IUserService _UserService { get; set; }
+
+
         protected override async System.Threading.Tasks.Task OnInitializedAsync()
         {
             base.OnInitialized();

+ 1 - 1
wispro.sp.web/Components/UserGradeSelect.razor

@@ -1,4 +1,4 @@
-@inject StaffGradeService _staffGradeService;
+
 
 <Select DataSource="@_StaffGrades"
         DefaultValue="@StaffGradeId"

+ 4 - 1
wispro.sp.web/Components/UserGradeSelect.razor.cs

@@ -4,14 +4,17 @@ using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using wispro.sp.entity;
+using wispro.sp.web.Services;
 
 namespace wispro.sp.web.Components
 {
-    public partial  class UserGradeSelect
+    public partial class UserGradeSelect
     {
         private List<StaffGrade> _StaffGrades;
         private StaffGrade _SelectedItem;
 
+        [Inject] StaffGradeService _staffGradeService{get;set;}
+
         [Parameter]
         public int? StaffGradeId { get; set; }
 

+ 1 - 1
wispro.sp.web/Layouts/LoginLayout.razor

@@ -4,7 +4,7 @@
     <Content Style="padding: 24px;min-height: 280px;">
         @Body
     </Content>
-    <Footer Style="text-align: center;height:50px;"> ©2021 Created by 小知识产权</Footer>
+    <Footer Style="text-align: center;height:50px;"> ©2021 Created by 小知识产权</Footer>
 </AntDesign.Layout>
 
 <style>

+ 12 - 2
wispro.sp.web/Models/CreateAppealModel.cs

@@ -32,11 +32,21 @@ namespace wispro.sp.web.Models
         public async Task Init(AppealTypeService _atService,PerformanceItem item,AppealType appealType)
         {
             FileList = new List<UploadFileItem>();
-            Item = item;
             AppealType = appealType;
             AppealRecord = new AppealRecord();
             AppealRecord.TypeId = appealType.Id;
-            AppealRecord.ItemId = item.Id;
+
+            if (item == null)
+            {
+                Item = new PerformanceItem();
+            }
+            else
+            {
+                Item = item;
+            }
+
+            AppealRecord.ItemId = Item.Id;
+
             AppealRecord.State = 0;
 
             if (AppealType != null)

+ 0 - 2
wispro.sp.web/Models/ReviewerAppealModel.cs

@@ -37,7 +37,6 @@ namespace wispro.sp.web.Models
             inputFieldValues = new List<InputFieldValue>();
             foreach (var field in inputFields)
             {
-                Console.WriteLine($"inputFields:{JsonSerializer.Serialize(field)}");
                 if (!string.IsNullOrEmpty(field.MapObjectField) && !string.IsNullOrEmpty(field.MapObjectFieldLabel))
                 {
                     List<InputFieldValue> temValues = new List<InputFieldValue>();
@@ -93,7 +92,6 @@ namespace wispro.sp.web.Models
                 }
                 else
                 {
-                    Console.WriteLine($"inputFields:{JsonSerializer.Serialize(field)}");
                     var fValue = new InputFieldValue();
                     fValue.InputField = field;
                     fValue.InputFieldId = field.Id;

+ 8 - 2
wispro.sp.web/Pages/AppCase/MyCaselist.razor

@@ -32,7 +32,13 @@
                     {
                         <PageHeader>
                             <PageHeaderTitle>基础点数统计</PageHeaderTitle>
-                            <PageHeaderExtra><Button Type="@ButtonType.Primary">缺失数据提报</Button></PageHeaderExtra>
+                            <PageHeaderExtra>
+                                @foreach(AppealType at in apTypeService.GetItems(1))
+                                {
+                                    <Button Type="@ButtonType.Primary" OnClick="()=>ShowModel(null,at)">@at.Name</Button>
+                                }
+                            
+                            </PageHeaderExtra>
                             <PageHeaderContent>
                                 <div style="border:1px solid #000000">
                                     <AntDesign.Row Align="center" Justify="center">
@@ -58,7 +64,7 @@
                                         <AntDesign.Col Span="4" style="border:1px solid #000000"><center>总计</center></AntDesign.Col>
                                     </AntDesign.Row>
                                     <AntDesign.Row>
-                                        <AntDesign.Col Span="2" style="border:1px solid #000000"><center>@_userService.CurrentUser.Name</center></AntDesign.Col>
+                                        <AntDesign.Col Span="2" style="border:1px solid #000000"><center>@_user.Name</center></AntDesign.Col>
                                         <AntDesign.Col Span="2" style="border:1px solid #000000"><center>@GetStatistics("新申请处理")</center></AntDesign.Col>
                                         <AntDesign.Col Span="2" style="border:1px solid #000000"><center>@GetStatistics("新申请审核")</center></AntDesign.Col>
                                         <AntDesign.Col Span="2" style="border:1px solid #000000"><center>@GetStatistics("OA处理")</center></AntDesign.Col>

+ 28 - 13
wispro.sp.web/Pages/AppCase/MyCaselist.razor.cs

@@ -11,6 +11,7 @@ using System.Text.Json;
 using System.Threading.Tasks;
 using wispro.sp.entity;
 using wispro.sp.share;
+using wispro.sp.web.Models;
 using wispro.sp.web.Services;
 
 
@@ -40,6 +41,7 @@ namespace wispro.sp.web.Pages.AppCase
         private List<StaffStatistics> MyStatistics;
         IEnumerable<PerformanceItem> selectedItems= new List<PerformanceItem>();
         private CalMonth HandlingCalMonth;
+        
 
         int _pageIndex = 1;
         int _pageSize = 10;
@@ -64,6 +66,7 @@ namespace wispro.sp.web.Pages.AppCase
 
         private bool isFirstInit = true;
         private Table<PerformanceItem> table;
+        private CurrentUser _user;
         protected async override Task OnInitializedAsync()
         {
             if (isFirstInit)
@@ -78,8 +81,8 @@ namespace wispro.sp.web.Pages.AppCase
 
             isFirstInit = false;
             await apTypeService.GetItems();
+            _user =await _userService.GetUser();
             StateHasChanged();
-            //Console.WriteLine($"OnInitializedAsync:[tota:{_total}\tPageIndex:{_pageIndex}\tPageSize:{_pageSize}]");
         }
 
         private async Task RefreshMyStatistics()
@@ -87,9 +90,10 @@ namespace wispro.sp.web.Pages.AppCase
             var HandlingCalMonth = await _CalMonthService.GetHandlingMonth();
             if (HandlingCalMonth != null)
             {
-                if (_userService.CurrentUser.Userid != null)
+                var _user = await _userService.GetUser(); ;
+                if (_user.Userid != null)
                 {
-                    MyStatistics = await _ItemService.CalMyStatistics(HandlingCalMonth.Year, HandlingCalMonth.Month, _userService.CurrentUser.Userid.Value);
+                    MyStatistics = await _ItemService.CalMyStatistics(HandlingCalMonth.Year, HandlingCalMonth.Month, _user.Userid.Value);
                 }
                 else
                 {
@@ -145,11 +149,12 @@ namespace wispro.sp.web.Pages.AppCase
 
         private async Task HandleTableChange(QueryModel<PerformanceItem> queryModel)
         {
-
+            var _user = await _userService.GetUser();
             if (_CurrentKey == tabList[0].Key)
             {
                 _loading = true;
-                var data = await _ItemService.Query(_userService.CurrentUser.Userid.Value, jxType.doing, queryModel);
+                
+                var data = await _ItemService.Query(_user.Userid.Value, jxType.doing, queryModel);
 
                 _Datas = data.Results;
                 _total = data.TotalCount;
@@ -159,7 +164,7 @@ namespace wispro.sp.web.Pages.AppCase
             else
             {
                 _loading = true;
-                var data = await _ItemService.Query(_userService.CurrentUser.Userid.Value, jxType.finished, queryModel);
+                var data = await _ItemService.Query(_user.Userid.Value, jxType.finished, queryModel);
 
                 _Datas = data.Results;
                 _total = data.TotalCount;
@@ -207,7 +212,6 @@ namespace wispro.sp.web.Pages.AppCase
 
         void ClearSelect(int itemId)
         {
-            //Console.WriteLine($"ClearSelcet:{itemId}");
             var respone = _ItemService.SaveFieldChange(itemId, strAgentFeedbackMemo,"");
             EditingItem = null;
 
@@ -252,7 +256,6 @@ namespace wispro.sp.web.Pages.AppCase
         {
             var templateOptions = new Models.CreateAppealModel();
             await templateOptions.Init(_atService,Item, appealType);
-            Console.WriteLine(JsonSerializer.Serialize(templateOptions));
 
             var modalConfig = new ModalOptions();
             modalConfig.Title = appealType.Name;
@@ -266,21 +269,35 @@ namespace wispro.sp.web.Pages.AppCase
 
             _modalRef.OnOpen = () =>
             {
-                Console.WriteLine("ModalRef OnOpen");
                 return Task.CompletedTask;
             };
 
             _modalRef.OnOk = async () =>
             {
-                Console.WriteLine(JsonSerializer.Serialize(templateOptions));
                 try
                 {
                     await _atService.CreateAppeal(templateOptions);
                     await _modalRef.CloseAsync();
-                    
+
+                    StateHasChanged();
+
+                    var SuccessConfig = new ConfirmOptions()
+                    {
+                        Content = @"保存申诉信息成功!"
+                    };
+
+                    //modalConfig.Footer = null;
+                    modalConfig.DestroyOnClose = true;
+                    _ModalService.Success(SuccessConfig);
+
                 }
                 catch (Exception ex)
                 {
+                    _ModalService.Error(new ConfirmOptions()
+                    {
+                        Title = "保存申诉信息错误",
+                        Content = ex.Message,
+                    });
                     //_ErrorMessage = ex.Message;
                 }
 
@@ -289,13 +306,11 @@ namespace wispro.sp.web.Pages.AppCase
 
             _modalRef.OnCancel = () =>
             {
-                Console.WriteLine("ModalRef OnCancel");
                 return Task.CompletedTask;
             };
 
             _modalRef.OnClose = () =>
             {
-                Console.WriteLine("ModalRef OnClose");
                 return Task.CompletedTask;
             };
             StateHasChanged();

+ 2 - 1
wispro.sp.web/Pages/AppCase/MyFistPage.razor.cs

@@ -27,7 +27,8 @@ namespace wispro.sp.web.Pages.AppCase
             _loading = true;
 
             //System.Diagnostics.Debug.WriteLine(_userService.CurrentUser.Userid);
-            var data = await _ItemService.GetMyList(_userService.CurrentUser.Userid.Value,jxType.doing);
+            var _user = await _userService.GetUser();
+            var data = await _ItemService.GetMyList(_user.Userid.Value,jxType.doing);
 
 
             _Datas = data.Results;

+ 0 - 1
wispro.sp.web/Pages/CustomerList.razor.cs

@@ -325,7 +325,6 @@ namespace wispro.sp.web.Pages
 
         private void HandleCancel(MouseEventArgs e)
         {
-            Console.WriteLine(e);
             _visible = false;
         }
     }

+ 6 - 15
wispro.sp.web/Pages/LoginPages.razor.cs

@@ -10,6 +10,8 @@ using Microsoft.IdentityModel.Tokens;
 using System.Linq;
 using System.Security.Claims;
 using Blazored.LocalStorage;
+using System;
+using System.Text.Json;
 
 namespace wispro.sp.web.Pages
 {
@@ -30,10 +32,9 @@ namespace wispro.sp.web.Pages
         {
             isLoading = true;
 
-            //var httpResponse = await Http.PostAsJsonAsync<loginDto>($"http://localhost:39476/api/account/Login", model);
-            //userToken result = await httpResponse.Content.ReadFromJsonAsync<userToken>();
+            
             bool result = await authService.LoginAsync(model);
-
+            
             if (result)
             {
                 navigation.NavigateTo("/Home");
@@ -41,20 +42,10 @@ namespace wispro.sp.web.Pages
             else
             {
                 _ = MsgSvr.Error($"用户名或密码错误");
-                //await js.InvokeVoidAsync("alert", "登入失敗");
+                
             }
-
-            //if (string.IsNullOrWhiteSpace(result?.Token) == false)
-            //{
-            //    _ = MsgSvr.Success($"登录成功");
-            //    //((AuthProvider)AuthProvider).MarkUserAsAuthenticated(result);
-            //}
-            //else
-            //{
-            //    _ = MsgSvr.Error($"用户名或密码错误");
-            //}
+            
             isLoading = false;
-            //await InvokeAsync(StateHasChanged);
         }
     }
 }

+ 1 - 1
wispro.sp.web/Pages/StaffGrade.razor

@@ -2,7 +2,7 @@
 
 @inject HttpClient Http
 @using AntDesign.TableModels
-@inject MessageService _message
+
 @using System.ComponentModel
 @using wispro.sp.share
 

+ 2 - 2
wispro.sp.web/Pages/StaffGrade.razor.cs

@@ -15,7 +15,8 @@ namespace wispro.sp.web.Pages
     public partial  class StaffGrade
     {
         [Inject] public StaffGradeService _sfService { get; set; }
-        
+        [Inject] MessageService _message { get; set; }
+
         private List<wispro.sp.entity.StaffGrade> staffGrades;
         IEnumerable<wispro.sp.entity.StaffGrade> selectedRows;
         
@@ -138,7 +139,6 @@ namespace wispro.sp.web.Pages
 
         private void HandleCancel(MouseEventArgs e)
         {
-            //Console.WriteLine(e);
             _visible = false;
         }
     }

+ 0 - 1
wispro.sp.web/Pages/StaffList.razor

@@ -326,7 +326,6 @@
 
     private void HandleCancel(MouseEventArgs e)
     {
-        Console.WriteLine(e);
         _visible = false;
     }
 }

+ 0 - 2
wispro.sp.web/Pages/UploadData.razor

@@ -112,12 +112,10 @@
 
     private void OnFinish(EditContext editContext)
     {
-        //Console.WriteLine($"Success:{JsonSerializer.Serialize(model)}");
     }
 
     private void OnFinishFailed(EditContext editContext)
     {
-        //Console.WriteLine($"Failed:{JsonSerializer.Serialize(model)}");
     }
 
     private List<File> files = new();

+ 4 - 1
wispro.sp.web/Pages/Welcome.razor

@@ -15,12 +15,15 @@
                 <Avatar size="large" src="https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png" />
             </div>
             <div class="content">
+                @if (_CurrentUser != null)
+                {
                 <div class="contentTitle">
-                    上午好,@(_CurrentUser.Name). 祝您一天愉快!
+                    @(_CurrentUser.Name)好, 祝您一天愉快!
                 </div>
                 <div>
                     合伙人 | 深圳威世博代理事务所 | 工作地:深圳
                 </div>
+                }
             </div>
         </div>
     </Content>

+ 36 - 25
wispro.sp.web/Pages/Welcome.razor.cs

@@ -36,36 +36,49 @@ namespace wispro.sp.web.Pages
         [Inject] ModalService _ModalService { get; set; }
 
         [Inject] MessageService _msgService { get; set; }
+        private Models.CurrentUser _user;
         
 
         protected override async System.Threading.Tasks.Task OnInitializedAsync()
         {
             await base.OnInitializedAsync();
-            _CurrentUser = _userService.CurrentUser;
-            _projectNotice = await ProjectService.GetProjectNoticeAsync();
-            //_activities = await ProjectService.GetActivitiesAsync();
-            AppealRecords = await _atService.GetUserAppeals(_CurrentUser.Userid);
+            _CurrentUser =await _userService.GetUser();
 
-            AppealRecords.Sort((a, b) =>
-            {
-                var sd = (a.ReviewTime == null) ? a.ReviewTime : a.CreateTime;
-                var ed = (b.ReviewTime == null) ? b.ReviewTime : b.CreateTime;
+            //Console.WriteLine(JsonSerializer.Serialize(_CurrentUser));
 
-                if (ed > sd)
-                {
-                    return 1;
-                }
-                else
+            if (_CurrentUser != null)
+            {
+                //_projectNotice = await ProjectService.GetProjectNoticeAsync();
+                //_activities = await ProjectService.GetActivitiesAsync();
+                AppealRecords = await _atService.GetUserAppeals(_CurrentUser.Userid);
+                //Console.WriteLine(JsonSerializer.Serialize(AppealRecords));
+                if (AppealRecords != null)
                 {
-                    return -1;
-                }
-                
-            });
+                    //_user = await _userService.GetUser();
+                    AppealRecords.Sort((a, b) =>
+                    {
+                        var sd = (a.ReviewTime == null) ? a.ReviewTime : a.CreateTime;
+                        var ed = (b.ReviewTime == null) ? b.ReviewTime : b.CreateTime;
 
-            foreach (AppealRecord at in AppealRecords)
+                        if (ed > sd)
+                        {
+                            return 1;
+                        }
+                        else
+                        {
+                            return -1;
+                        }
+
+                    });
+                }
+            }
+            else
             {
-                System.Diagnostics.Debug.WriteLine(at.Item.CaseNo);
+                //NavigationManager.
             }
+
+            StateHasChanged();
+            
         }
 
         async Task ShowModel(AppealRecord appealRecord)
@@ -86,13 +99,13 @@ namespace wispro.sp.web.Pages
 
             _modalRef.OnOpen = () =>
             {
-                Console.WriteLine("ModalRef OnOpen");
+                //Console.WriteLine("ModalRef OnOpen");
                 return Task.CompletedTask;
             };
 
             _modalRef.OnOk = async () =>
             {
-                Console.WriteLine(JsonSerializer.Serialize(templateOptions));
+                //Console.WriteLine(JsonSerializer.Serialize(templateOptions));
                 try
                 {
                     await _atService.ReviewerAppeal(templateOptions);
@@ -136,21 +149,19 @@ namespace wispro.sp.web.Pages
                         Title = "审核错误",
                         Content = ex.Message,
                     });
-                    //_ErrorMessage = ex.Message;
+                    
                 }
 
-                //return Task.CompletedTask;
+                
             };
 
             _modalRef.OnCancel = () =>
             {
-                Console.WriteLine("ModalRef OnCancel");
                 return Task.CompletedTask;
             };
 
             _modalRef.OnClose = () =>
             {
-                Console.WriteLine("ModalRef OnClose");
                 return Task.CompletedTask;
             };
             StateHasChanged();

+ 2 - 1
wispro.sp.web/Program.cs

@@ -39,7 +39,8 @@ namespace wispro.sp.web
             builder.Services.AddScoped<CalMonthServices, CalMonthServices>();
             builder.Services.AddScoped<IAgentFeedBackMemoItemsService, AgentFeedbackMemoItemsServices>();
             builder.Services.AddScoped<AppealTypeService, AppealTypeService>();
-            
+            builder.Services.AddScoped<IHttpService, HttpService>();
+
             await builder.Build().RunAsync();
         }
     }

+ 49 - 20
wispro.sp.web/Services/AppealTypeService.cs

@@ -16,11 +16,11 @@ namespace wispro.sp.web.Services
 {
     public class AppealTypeService
     {
-        private readonly HttpClient _httpClient;
+        private readonly IHttpService _httpClient;
         private readonly JwtAuthenticationStateProvider _jwt;
         private  List<AppealType> AppealTypes;
 
-        public AppealTypeService(HttpClient httpClient, AuthenticationStateProvider jwt)
+        public AppealTypeService(IHttpService httpClient, AuthenticationStateProvider jwt)
         {
             _httpClient = httpClient;
             _jwt = (JwtAuthenticationStateProvider)jwt;
@@ -30,13 +30,13 @@ namespace wispro.sp.web.Services
 
         public async Task<AppealRecord> getAppealRecord(int appealRecordId)
         {
-            var data = await _httpClient.GetFromJsonAsync<AppealRecord>($"http://localhost:39476/api/Appeal/GetAppealRecord?Id={appealRecordId}");
+            var data = await _httpClient.Get<AppealRecord>($"Appeal/GetAppealRecord?Id={appealRecordId}");
             return data;
         }
 
         public async Task<List<InputFieldValue>> GetInputFieldValues(int id, int state)
         {
-            var data = await _httpClient.GetFromJsonAsync<List<InputFieldValue>>($"http://localhost:39476/api/Appeal/GetInputFieldValues?Id={id}&state={state}");
+            var data = await _httpClient.Get<List<InputFieldValue>>($"Appeal/GetInputFieldValues?Id={id}&state={state}");
             return data;
         }
 
@@ -44,22 +44,25 @@ namespace wispro.sp.web.Services
         {
             if (AppealTypes == null)
             {
-                AppealTypes = await _httpClient.GetFromJsonAsync<List<AppealType>>($"http://localhost:39476/api/Appeal/GetAppealTypes");
+                AppealTypes = await _httpClient.Get<List<AppealType>>($"Appeal/GetAppealTypes");
                 
             }
             return AppealTypes;
         }
 
+        public List<AppealType> GetItems(int Type)
+        {
+            return AppealTypes.Where<AppealType>(at => at.Type == Type).ToList();
+        }
         public List<AppealType> GetItems(PerformanceItem item)
         {
             List<AppealType> retList = new List<AppealType>();
 
-            foreach (var at in AppealTypes)
+            foreach (var at in GetItems(0))
             {
                 if (!string.IsNullOrWhiteSpace(at.CanDoExpress))
                 {
                     var interpreter = new Interpreter();
-                    //Console.WriteLine(at.CanDoExpress);
                     Func<PerformanceItem, bool> func = interpreter.ParseAsDelegate<Func<PerformanceItem, bool>>(at.CanDoExpress, "p");
                     bool result = func.Invoke(item);
                     
@@ -79,7 +82,7 @@ namespace wispro.sp.web.Services
 
         public async Task<List<AppealRecord>> GetUserAppeals(int? userid)
         {
-            var data = await _httpClient.GetFromJsonAsync<List<AppealRecord>>($"http://localhost:39476/api/Appeal/GetAppealRecords?userId={userid}");
+            var data = await _httpClient.Get<List<AppealRecord>>($"Appeal/GetAppealRecords?userId={userid}");
             return data;
         }
 
@@ -87,7 +90,7 @@ namespace wispro.sp.web.Services
         {
             if (AppealTypes == null)
             {
-                AppealTypes = await _httpClient.GetFromJsonAsync<List<AppealType>>($"http://localhost:39476/api/Appeal/GetAppealTypes");
+                AppealTypes = await _httpClient.Get<List<AppealType>>($"Appeal/GetAppealTypes");
             }
 
             var retData = AppealTypes.Where<AppealType>(ap => ap.Id == appealTypeId).FirstOrDefault();
@@ -97,14 +100,13 @@ namespace wispro.sp.web.Services
 
         public async Task<List<InputField>> GetInputFields(int appealTypeId,int State)
         {
-            Console.WriteLine($"begin GetInputFields: appealTypeId={appealTypeId};State={State}");
-            var data = await _httpClient.GetFromJsonAsync<List<InputField>>($"http://localhost:39476/api/Appeal/GetInputField?appealTypeId={appealTypeId}&state={State}");
+            var data = await _httpClient.Get<List<InputField>>($"Appeal/GetInputField?appealTypeId={appealTypeId}&state={State}");
             return data;
         }
 
         public async Task<List<AttachFile>> GetAppealRecordAttachFiles(int appealRecordId)
         {
-            var data = await _httpClient.GetFromJsonAsync<List<AttachFile>>($"http://localhost:39476/api/Appeal/GetAppealRecordAttachFiles?appealRecordId={appealRecordId}");
+            var data = await _httpClient.Get<List<AttachFile>>($"Appeal/GetAppealRecordAttachFiles?appealRecordId={appealRecordId}");
             return data;
         }
 
@@ -120,7 +122,7 @@ namespace wispro.sp.web.Services
                 attachFiles.Add(atfile);
             }
 
-            string strUrl = $"http://localhost:39476/api/Appeal/CreateAppeal?ItemId={model.Item.Id}&typeid={model.AppealType.Id}&reviewerId={model.AppealRecord.ReviewerId}";
+            string strUrl = $"Appeal/CreateAppeal?ItemId={model.Item.Id}&typeid={model.AppealType.Id}&reviewerId={model.AppealRecord.ReviewerId}";
             AppealObject appealObject = new AppealObject();
             appealObject.attachFiles = attachFiles;
             appealObject.inputFieldValues = model.inputFieldValues;
@@ -129,15 +131,29 @@ namespace wispro.sp.web.Services
                 fValue.InputField = null;
             }
 
-            var data = await _httpClient.PostAsJsonAsync<AppealObject>(strUrl, appealObject);
+            try
+            {
+                var data = await _httpClient.Post<ApiSaveResponse>(strUrl, appealObject);
+
+                if (!data.Success)
+                {
+                    if (!data.Success)
+                    {
+                        throw new ApplicationException(data.ErrorMessage);
+                    }
+                }
+            }
+            catch(Exception ex)
+            {
+                throw ex;
+            }
 
-            Console.WriteLine(JsonSerializer.Serialize(data));
         }
 
         public async Task ReviewerAppeal(ReviewerAppealModel model)
         {
 
-            string strUrl = $"http://localhost:39476/api/Appeal/ReviewerAppeal?appealRecordId={model.AppealRecord.Id}";
+            string strUrl = $"Appeal/ReviewerAppeal?appealRecordId={model.AppealRecord.Id}";
             AppealObject appealObject = new AppealObject();
             appealObject.inputFieldValues = model.inputFieldValues;
 
@@ -146,13 +162,26 @@ namespace wispro.sp.web.Services
                 fValue.InputField = null;
             }
 
-            var data = await _httpClient.PostAsJsonAsync<AppealObject>(strUrl, appealObject);
+            try
+            {
+                var data = await _httpClient.Post<ApiSaveResponse>(strUrl, appealObject);
 
-            if (!data.IsSuccessStatusCode)
+                if (!data.Success)
+                {
+                    throw new ApplicationException(data.ErrorMessage);
+                }
+                
+            }
+            catch(Exception ex)
             {
-                string strContent = await data.Content.ReadAsStringAsync();
-                throw new Exception(strContent);
+                throw ex;
             }
+
+            //if (!data.IsSuccessStatusCode)
+            //{
+            //    string strContent = await data.Content.ReadAsStringAsync();
+            //    throw new Exception(strContent);
+            //}
         }
         
         

+ 10 - 13
wispro.sp.web/Services/AuthService.cs

@@ -1,6 +1,6 @@
 using Blazored.LocalStorage;
 using Microsoft.AspNetCore.Components.Authorization;
-using Newtonsoft.Json;
+
 using System;
 using System.Collections.Generic;
 using System.Linq;
@@ -10,17 +10,18 @@ using System.Text;
 using System.Threading.Tasks;
 using wispro.sp.share.webViewObject;
 using wispro.sp.web.Auth;
+using System.Text.Json;
 
 namespace wispro.sp.web.Services
 {
     public class AuthService : IAuthService
     {
         private readonly ILocalStorageService localStorageService;
-        private readonly HttpClient httpClient;
+        private readonly IHttpService httpClient;
         private readonly AuthenticationStateProvider authenticationStateProvider;
         private IUserService UserService;
 
-        public AuthService(ILocalStorageService localStorageService, HttpClient httpClient, AuthenticationStateProvider authenticationStateProvider, IUserService UserService)
+        public AuthService(ILocalStorageService localStorageService, IHttpService httpClient, AuthenticationStateProvider authenticationStateProvider, IUserService UserService)
         {
             this.localStorageService = localStorageService;
             this.httpClient = httpClient;
@@ -32,22 +33,18 @@ namespace wispro.sp.web.Services
         {
             bool result = false;
 
-            var httpResponse = await httpClient.PostAsJsonAsync<loginDto>($"http://localhost:39476/api/account/Login", userInfo);
+            var httpResponse = await httpClient.Post<userToken>($"account/Login", userInfo);
 
-            if (httpResponse.IsSuccessStatusCode)
+            if (httpResponse.StatusCode != System.Net.HttpStatusCode.NotFound)
             {
-                userToken userToken = await httpResponse.Content.ReadFromJsonAsync<userToken>();
-                await localStorageService.SetItemAsync<string>("authToken", userToken.Token);
+                userToken userToken = httpResponse;
+                await localStorageService.SetItemAsync<userToken>("authToken", userToken);
 
                 ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserAuthentication(userToken.Token);
-
-                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", userToken.Token);
-                
-                UserService.CurrentUser = new Models.CurrentUser() { Name = userToken.Name,Userid = userToken.UserId};
                 
                 result = true;
             }
-
+            //System.Threading.Thread.Sleep(1000);
             return result;
         }
 
@@ -55,7 +52,7 @@ namespace wispro.sp.web.Services
         {
             await localStorageService.RemoveItemAsync("authToken");
             ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
-            httpClient.DefaultRequestHeaders.Authorization = null;
+            //httpClient.DefaultRequestHeaders.Authorization = null;
         }
     }
 }

+ 4 - 6
wispro.sp.web/Services/CalMonthServices.cs

@@ -11,10 +11,9 @@ namespace wispro.sp.web.Services
 {
     public class CalMonthServices
     {
-        private readonly HttpClient _httpClient;
-        private readonly ILocalStorageService _localStorageService;
+        private readonly IHttpService  _httpClient;
         
-        public CalMonthServices(HttpClient httpClient)
+        public CalMonthServices(IHttpService httpClient)
         {
             _httpClient = httpClient;
             
@@ -23,12 +22,11 @@ namespace wispro.sp.web.Services
         {
             try
             {
-                var data = await _httpClient.GetFromJsonAsync<CalMonth>($"http://localhost:39476/api/CalMonth/GetHandlingMonth");
+                var data = await _httpClient.Get<CalMonth>($"CalMonth/GetHandlingMonth");
                 return data;
             }
-            catch(Exception ex)
+            catch
             {
-                Console.WriteLine(ex.ToString());
                 return null;
             }
         }

+ 110 - 0
wispro.sp.web/Services/HttpService.cs

@@ -0,0 +1,110 @@
+using Blazored.LocalStorage;
+using Microsoft.AspNetCore.Components;
+using Microsoft.AspNetCore.Components.Authorization;
+using Microsoft.Extensions.Configuration;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Net;
+using System.Net.Http;
+using System.Net.Http.Headers;
+using System.Net.Http.Json;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using wispro.sp.share.webViewObject;
+using wispro.sp.web.Auth;
+using wispro.sp.web.Utils;
+
+namespace wispro.sp.web.Services
+{
+    public interface IHttpService
+    {
+        Task<T> Get<T>(string uri);
+        Task<T> Post<T>(string uri, object value);
+    }
+
+    public class HttpService:IHttpService
+    {
+        private HttpClient _httpClient;
+        private NavigationManager _navigationManager;
+        private ILocalStorageService _localStorageService;
+        private IConfiguration _configuration;
+        //private IAuthService _authService;
+        private AuthenticationStateProvider authenticationStateProvider;
+
+        public HttpService(
+            HttpClient httpClient,
+            NavigationManager navigationManager,
+            ILocalStorageService localStorageService,
+            IConfiguration configuration,
+            AuthenticationStateProvider authService
+        )
+        {
+            _httpClient = httpClient;
+            _navigationManager = navigationManager;
+            _localStorageService = localStorageService;
+            _configuration = configuration;
+            authenticationStateProvider = authService;
+        }
+
+        public async Task<T> Get<T>(string uri)
+        {
+            
+            var request = new HttpRequestMessage(HttpMethod.Get, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
+            return await sendRequest<T>(request);
+        }
+
+        public async Task<T> Post<T>(string uri, object value)
+        {
+            var request = new HttpRequestMessage(HttpMethod.Post, $"{_configuration.GetValue<string>("APIUrl")}{uri}");
+            request.Content = new StringContent(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");
+            return await sendRequest<T>(request);
+        }
+
+        private async Task<T> sendRequest<T>(HttpRequestMessage request)
+        {
+            // add jwt auth header if user is logged in and request is to the api url
+            try
+            {
+                var user = await _localStorageService.GetItemAsync<userToken>("authToken");
+                var isApiUrl = !request.RequestUri.IsAbsoluteUri;
+
+                if (user != null) // && isApiUrl)
+                {
+                    //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", user.Token);
+
+                    //將token取出轉為claim
+                    var claims = JwtParser.ParseClaimsFromJwt(user.Token);
+
+                    //在每次request的header中帶入bearer token
+                    _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("bearer", user.Token);
+                }
+            }
+            catch(Exception ex) {
+                Console.WriteLine(ex.ToString());
+            }
+
+            using HttpResponseMessage response = await _httpClient.SendAsync(request);
+
+            // auto logout on 401 response
+            if (response.StatusCode == HttpStatusCode.Unauthorized)
+            {
+                _httpClient.DefaultRequestHeaders.Authorization = null;
+                await _localStorageService.RemoveItemAsync("authToken");
+                ((JwtAuthenticationStateProvider)authenticationStateProvider).NotifyUserLogOut();
+                return default;
+            }
+
+            // throw exception on error response
+            if (!response.IsSuccessStatusCode)
+            {
+                var error = await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
+                throw new Exception(error["message"]);
+            }
+            var retData =await response.Content.ReadFromJsonAsync<T>();
+            
+            return retData;
+        }
+    }
+}

+ 9 - 21
wispro.sp.web/Services/PerformanceItemServices.cs

@@ -14,10 +14,10 @@ namespace wispro.sp.web.Services
 {
     public class PerformanceItemServices
     {
-        private readonly HttpClient _httpClient;
+        private readonly IHttpService _httpClient;
         private readonly JwtAuthenticationStateProvider _jwt;
 
-        public PerformanceItemServices(HttpClient httpClient, AuthenticationStateProvider jwt)
+        public PerformanceItemServices(IHttpService httpClient, AuthenticationStateProvider jwt)
         {
             _httpClient = httpClient;
             _jwt = (JwtAuthenticationStateProvider)jwt;
@@ -25,20 +25,20 @@ namespace wispro.sp.web.Services
 
         public async Task<ListApiResponse<PerformanceItem>> GetItems(int _pageIndex,int _pageSize)
         {
-            ListApiResponse<PerformanceItem> data = await _httpClient.GetFromJsonAsync<ListApiResponse<PerformanceItem>>($"http://localhost:39476/api/PerformanceItem/Query?pageIndex={_pageIndex}&pageSize={_pageSize}");
+            ListApiResponse<PerformanceItem> data = await _httpClient.Get<ListApiResponse<PerformanceItem>>($"PerformanceItem/Query?pageIndex={_pageIndex}&pageSize={_pageSize}");
             return data;
 
         }
 
         public async Task<ApiSaveResponse> SaveFieldChange(int id,string Field,string value)
         {
-            ApiSaveResponse data = await _httpClient.GetFromJsonAsync<ApiSaveResponse>($"http://localhost:39476/api/PerformanceItem/UpdateFieldValue?id={id}&field={Field}&value={value}");
+            ApiSaveResponse data = await _httpClient.Get<ApiSaveResponse>($"PerformanceItem/UpdateFieldValue?id={id}&field={Field}&value={value}");
             return data;
         }
 
         public async Task<ListApiResponse<PerformanceItem>> GetMyList(int userid,jxType type,int pageIndex=1,int pageSize=5)
         {
-            ListApiResponse<PerformanceItem> data = await _httpClient.GetFromJsonAsync<ListApiResponse<PerformanceItem>>($"http://localhost:39476/api/PerformanceItem/GetMyList?userid={userid}&Type={Convert.ToInt32(type)}&pageIndex={pageIndex}&pageSize={pageSize}");
+            ListApiResponse<PerformanceItem> data = await _httpClient.Get<ListApiResponse<PerformanceItem>>($"PerformanceItem/GetMyList?userid={userid}&Type={Convert.ToInt32(type)}&pageIndex={pageIndex}&pageSize={pageSize}");
             return data;
         }
 
@@ -98,48 +98,36 @@ namespace wispro.sp.web.Services
                     {
                         case AntDesign.TableFilterCondition.And:
                             condition.LogicOperate = LogicEnum.And;
-                            //expressTree.AddCondition. (LogicEnum.And, condition);
-                            //Console.WriteLine($"添加条件:{condition.FieldName} {condition.Operator} {condition.Value} {condition.ValueType} AND");
-                            break;
+                             break;
                         case AntDesign.TableFilterCondition.Or:
                             condition.LogicOperate = LogicEnum.Or;
-                            //expressTree.AddCondition(LogicEnum.Or, condition);
-                            //Console.WriteLine($"添加条件:{condition.FieldName} {condition.Operator} {condition.Value} {condition.ValueType}  OR");
                             break;
                         default:
                             condition.LogicOperate = LogicEnum.And;
-                            //expressTree.AddCondition(LogicEnum.And, condition);
-                            //Console.WriteLine($"添加条件:{condition.FieldName} {condition.Operator} {condition.Value} {condition.ValueType}  AND");
                             break;
                     }
 
-                    //Console.WriteLine( expressTree.ToString());
                     query.ConditionTree.Add(condition);
                     
                 }
             }
 
-            
-
             query.Sorts =new  List<OrderField>();
             foreach(var sort in queryModel.SortModel)
             {
-                //Console.WriteLine($"{sort.FieldName}\t{sort.Sort}");
                 if (!string.IsNullOrEmpty(sort.Sort))
                 {
                     query.Sorts.Add(new OrderField() { FieldName = sort.FieldName, Sort = (sort.Sort == "descend" ? 1 : 0) });
                 }
             }
-            var data = await _httpClient.PostAsJsonAsync($"http://localhost:39476/api/PerformanceItem/QueryFilter",query);
+            var data = await _httpClient.Post<ListApiResponse<PerformanceItem>>($"PerformanceItem/QueryFilter",query);
 
-            var ret =  await data.Content.ReadFromJsonAsync<ListApiResponse<PerformanceItem>>();
-            return ret;
+            return data;
         }
 
         public async Task<List<StaffStatistics>> CalMyStatistics(int year, int month, int? userid = null)
         {
-
-            var data = await _httpClient.GetFromJsonAsync<List<StaffStatistics>>($"http://localhost:39476/api/PerformanceItem/CalMyStatistics?userid={userid}&year={year}&month={month}");
+            var data = await _httpClient.Get<List<StaffStatistics>>($"PerformanceItem/CalMyStatistics?userid={userid}&year={year}&month={month}");
             return data;
         }
     }

+ 9 - 16
wispro.sp.web/Services/StaffGradeService.cs

@@ -14,10 +14,10 @@ namespace wispro.sp.web.Services
 {
     public class StaffGradeService
     {
-        private readonly HttpClient _httpClient;
+        private readonly IHttpService _httpClient;
         private readonly JwtAuthenticationStateProvider _jwt;
 
-        public StaffGradeService(HttpClient httpClient, AuthenticationStateProvider jwt)
+        public StaffGradeService(IHttpService httpClient, AuthenticationStateProvider jwt)
         {
             _httpClient = httpClient;
             _jwt = (JwtAuthenticationStateProvider)jwt;
@@ -27,7 +27,7 @@ namespace wispro.sp.web.Services
         {
             try
             {
-                var _StaffGrade = await _httpClient.GetFromJsonAsync<List<StaffGrade>>($"http://localhost:39476/api/StaffGrade/GetAll");
+                var _StaffGrade = await _httpClient.Get<List<StaffGrade>>($"StaffGrade/GetAll");
                 return _StaffGrade;
             }
             catch(Exception ex)
@@ -44,23 +44,16 @@ namespace wispro.sp.web.Services
 
         public async Task<ApiSaveResponse> Save(StaffGrade staffGrade)
         {
-            var data = await _httpClient.PostAsJsonAsync<StaffGrade>($"http://localhost:39476/api/StaffGrade/Save", staffGrade);
-
-            if (data.IsSuccessStatusCode)
+            try
             {
-                ApiSaveResponse result = await data.Content.ReadFromJsonAsync<ApiSaveResponse>();
-                //await Task.Delay(1000);
-                return result;
+                var data = await _httpClient.Post<ApiSaveResponse>($"StaffGrade/Save", staffGrade);
+                return data;
             }
-            else
+            catch(Exception ex)
             {
-                if(data.StatusCode ==  System.Net.HttpStatusCode.Unauthorized)
-                {
-                    _jwt.NotifyUserLogOut();
-                }
-
-                return new ApiSaveResponse() { Success = false , ErrorMessage = $"请求发生错误 {data.StatusCode}" };
+                return new ApiSaveResponse() { Success = false, ErrorMessage = $"请求发生错误!\r\n {ex.Message}" };
             }
+            
         }
     }
 }

+ 31 - 18
wispro.sp.web/Services/UserService.cs

@@ -10,24 +10,28 @@ using System.Security.Claims;
 using System.Collections.Generic;
 using wispro.sp.entity;
 using System;
+using wispro.sp.share.webViewObject;
+using System.Text.Json;
 
 namespace wispro.sp.web.Services
 {
     public interface IUserService
     {
-        CurrentUser CurrentUser { get; set; }
+        //CurrentUser CurrentUser { get; set; }
 
         Task<List<Staff>> GetAll();
+
+        Task<CurrentUser> GetUser();
     }
 
     public class UserService : IUserService
     {
-        private readonly HttpClient _httpClient;
+        private readonly IHttpService  _httpClient;
         private readonly JwtAuthenticationStateProvider _jwt;
         private readonly ILocalStorageService _localStorageService;
-        private CurrentUser _CurrentUser= new CurrentUser() { Name = "" };
+        //private CurrentUser _CurrentUser= new CurrentUser() { Name = "" };
 
-        public UserService(HttpClient httpClient, ILocalStorageService localStorageService, AuthenticationStateProvider jwt)
+        public UserService(IHttpService httpClient, ILocalStorageService localStorageService, AuthenticationStateProvider jwt)
         {
             _httpClient = httpClient;
             _localStorageService = localStorageService;
@@ -35,24 +39,31 @@ namespace wispro.sp.web.Services
         }
 
 
-        public CurrentUser CurrentUser
-        {
-            get
-            {
-                return _CurrentUser;
-            }
-            set
-            {
-                _CurrentUser = value;
-            }
+        //public CurrentUser CurrentUser
+        //{
+        //    get
+        //    {
+        //        return _CurrentUser;
+        //    }
+        //    set
+        //    {
+        //        _CurrentUser = value;
+        //    }
             
-        }
+        //}
 
         public async Task<CurrentUser> GetUser()
         {
             CurrentUser _user = new CurrentUser();
-            var tokenInLocalStorage = await _localStorageService.GetItemAsStringAsync("authToken");
-            var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage);
+            var tokenInLocalStorage = await _localStorageService.GetItemAsync<userToken>("authToken");
+
+            if (tokenInLocalStorage == null)
+            {
+                _jwt.NotifyUserLogOut();
+                return null;
+            }
+
+            var claims = JwtParser.ParseClaimsFromJwt(tokenInLocalStorage.Token);
 
             foreach (Claim claim in claims)
             {
@@ -63,6 +74,8 @@ namespace wispro.sp.web.Services
                 }
             }
 
+            _user.Userid = tokenInLocalStorage.UserId;
+
             return _user;
         }
 
@@ -70,7 +83,7 @@ namespace wispro.sp.web.Services
         {
             try
             {
-                var _StaffGrade = await _httpClient.GetFromJsonAsync<List<Staff>>($"http://localhost:39476/api/Staff/GetAll");
+                var _StaffGrade = await _httpClient.Get<List<Staff>>($"Staff/GetAll");
                 return _StaffGrade;
             }
             catch (Exception ex)

+ 1 - 1
wispro.sp.web/wispro.sp.web.csproj

@@ -31,7 +31,7 @@
     <PackageReference Include="AntDesign.ProLayout" Version="0.1.8" />
     <PackageReference Include="Blazored.LocalStorage" Version="4.1.5" />
     <PackageReference Include="DynamicExpresso.Core" Version="2.9.3" />
-    <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="5.0.9" />
+    <PackageReference Include="Microsoft.AspNetCore.Authorization" Version="6.0.0" />
     <PackageReference Include="Microsoft.AspNetCore.Authorization.Policy" Version="2.2.0" />
     <PackageReference Include="Microsoft.AspNetCore.Components.Authorization" Version="5.0.9" />
     <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="5.0.0" />

+ 3 - 1
wispro.sp.web/wwwroot/appsettings.json

@@ -15,5 +15,7 @@
     "MenuHeaderRender": true,
     "HeaderHeight": 48
 
-  }
+  },
+
+  "APIUrl": "http://localhost:39476/api/"
 }

+ 1 - 1
wispro.sp.web/wwwroot/index.html

@@ -218,7 +218,7 @@
             <!--<div style="display: flex; justify-content: center; align-items: center;">
                 <img src="images/小美logo.png" width="32"
                     style="margin-right: 8px;" />
-                小知识产权
+                小知识产权
             </div>-->
         </div>
     </div>