> whereExpression, PageModel page);
18 | PageList GetPageList
(Expression> whereExpression, PageModel page);
19 | Task> GetPageListAsync(Expression> whereExpression, PageModel page);
20 | Task> GetPageListAsync(Expression> whereExpression, PageModel page);
21 | PageList GetPageList(Expression> whereExpression, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
22 | Task> GetPageListAsync(Expression> whereExpression, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
23 | PageList GetPageList
(Expression> whereExpression, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
24 | Task> GetPageListAsync(Expression> whereExpression, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
25 | PageList GetPageList(List conditionalList, PageModel page);
26 | Task> GetPageListAsync(List conditionalList, PageModel page);
27 | PageList GetPageList(List conditionalList, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
28 | Task> GetPageListAsync(List conditionalList, PageModel page, Expression> orderByExpression = null, OrderByType orderByType = OrderByType.Asc);
29 | T GetById(dynamic id);
30 | Task GetByIdAsync(dynamic id);
31 | T GetSingle(Expression> whereExpression);
32 | Task GetSingleAsync(Expression> whereExpression);
33 | T GetFirst(Expression> whereExpression);
34 | Task GetFirstAsync(Expression> whereExpression);
35 | bool Insert(T obj);
36 | Task InsertAsync(T obj);
37 | bool InsertRange(List objs);
38 | Task InsertRangeAsync(List objs);
39 | int InsertReturnIdentity(T obj);
40 | Task InsertReturnIdentityAsync(T obj);
41 | long InsertReturnBigIdentity(T obj);
42 | Task InsertReturnBigIdentityAsync(T obj);
43 | bool DeleteByIds(dynamic[] ids);
44 | Task DeleteByIdsAsync(dynamic[] ids);
45 | bool Delete(dynamic id);
46 | Task DeleteAsync(dynamic id);
47 | bool Delete(T obj);
48 | Task DeleteAsync(T obj);
49 | bool Delete(Expression> whereExpression);
50 | Task DeleteAsync(Expression> whereExpression);
51 | bool Update(T obj);
52 | Task UpdateAsync(T obj);
53 | bool UpdateRange(List objs);
54 | bool InsertOrUpdate(T obj);
55 | Task InsertOrUpdateAsync(T obj);
56 | Task UpdateRangeAsync(List objs);
57 | bool IsAny(Expression> whereExpression);
58 | Task IsAnyAsync(Expression> whereExpression);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/BlogAgent.Domain/Domain/Model/AgentOutputs.cs:
--------------------------------------------------------------------------------
1 | using System.Text.Json.Serialization;
2 |
3 | namespace BlogAgent.Domain.Domain.Model
4 | {
5 | ///
6 | /// 资料收集结果的结构化输出
7 | ///
8 | public class ResearchOutput
9 | {
10 | [JsonPropertyName("topic_analysis")]
11 | public string TopicAnalysis { get; set; } = string.Empty;
12 |
13 | [JsonPropertyName("key_points")]
14 | public List KeyPoints { get; set; } = new();
15 |
16 | [JsonPropertyName("technical_details")]
17 | public List TechnicalDetails { get; set; } = new();
18 |
19 | [JsonPropertyName("code_examples")]
20 | public List CodeExamples { get; set; } = new();
21 |
22 | [JsonPropertyName("references")]
23 | public List References { get; set; } = new();
24 | }
25 |
26 | public class KeyPoint
27 | {
28 | [JsonPropertyName("importance")]
29 | public int Importance { get; set; } // 1-3, 3最高
30 |
31 | [JsonPropertyName("content")]
32 | public string Content { get; set; } = string.Empty;
33 | }
34 |
35 | public class TechnicalDetail
36 | {
37 | [JsonPropertyName("title")]
38 | public string Title { get; set; } = string.Empty;
39 |
40 | [JsonPropertyName("description")]
41 | public string Description { get; set; } = string.Empty;
42 | }
43 |
44 | public class CodeExample
45 | {
46 | [JsonPropertyName("language")]
47 | public string Language { get; set; } = string.Empty;
48 |
49 | [JsonPropertyName("code")]
50 | public string Code { get; set; } = string.Empty;
51 |
52 | [JsonPropertyName("description")]
53 | public string Description { get; set; } = string.Empty;
54 | }
55 |
56 | ///
57 | /// 博客初稿的结构化输出
58 | ///
59 | public class DraftOutput
60 | {
61 | [JsonPropertyName("title")]
62 | public string Title { get; set; } = string.Empty;
63 |
64 | [JsonPropertyName("introduction")]
65 | public string Introduction { get; set; } = string.Empty;
66 |
67 | [JsonPropertyName("sections")]
68 | public List Sections { get; set; } = new();
69 |
70 | [JsonPropertyName("conclusion")]
71 | public string Conclusion { get; set; } = string.Empty;
72 |
73 | [JsonPropertyName("word_count")]
74 | public int WordCount { get; set; }
75 | }
76 |
77 | public class ContentSection
78 | {
79 | [JsonPropertyName("heading")]
80 | public string Heading { get; set; } = string.Empty;
81 |
82 | [JsonPropertyName("content")]
83 | public string Content { get; set; } = string.Empty;
84 |
85 | [JsonPropertyName("subsections")]
86 | public List? Subsections { get; set; }
87 | }
88 |
89 | ///
90 | /// 审查结果的结构化输出
91 | ///
92 | public class ReviewOutput
93 | {
94 | [JsonPropertyName("overall_score")]
95 | public int OverallScore { get; set; }
96 |
97 | [JsonPropertyName("accuracy")]
98 | public ScoreDetail Accuracy { get; set; } = new();
99 |
100 | [JsonPropertyName("logic")]
101 | public ScoreDetail Logic { get; set; } = new();
102 |
103 | [JsonPropertyName("originality")]
104 | public ScoreDetail Originality { get; set; } = new();
105 |
106 | [JsonPropertyName("formatting")]
107 | public ScoreDetail Formatting { get; set; } = new();
108 |
109 | [JsonPropertyName("recommendation")]
110 | public string Recommendation { get; set; } = string.Empty; // "通过", "需修改", "不通过"
111 |
112 | [JsonPropertyName("summary")]
113 | public string Summary { get; set; } = string.Empty;
114 | }
115 |
116 | public class ScoreDetail
117 | {
118 | [JsonPropertyName("score")]
119 | public int Score { get; set; }
120 |
121 | [JsonPropertyName("issues")]
122 | public List Issues { get; set; } = new();
123 | }
124 | }
125 |
--------------------------------------------------------------------------------
/BlogAgent.Domain/Services/Agents/ReviewerAgent.cs:
--------------------------------------------------------------------------------
1 | using BlogAgent.Domain.Services.Agents.Base;
2 | using BlogAgent.Domain.Common.Extensions;
3 | using BlogAgent.Domain.Domain.Dto;
4 | using BlogAgent.Domain.Domain.Enum;
5 | using BlogAgent.Domain.Repositories;
6 | using Microsoft.Extensions.Logging;
7 |
8 | namespace BlogAgent.Domain.Services.Agents
9 | {
10 | ///
11 | /// 质量审查专家Agent
12 | ///
13 | [ServiceDescription(typeof(ReviewerAgent), Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped)]
14 | public class ReviewerAgent : BaseAgentService
15 | {
16 | public override string AgentName => "质量审查专家";
17 |
18 | public override AgentType AgentType => AgentType.Reviewer;
19 |
20 | protected override string Instructions => @"你是一位严格的技术内容审查专家,负责对博客文章进行全面质量评估。
21 |
22 | **审查标准:**
23 |
24 | 1. **准确性(40分)**:
25 | - 技术概念定义是否准确
26 | - 代码示例是否正确可运行
27 | - 引用数据是否真实可靠
28 | - 是否包含过时或错误信息
29 |
30 | 2. **逻辑性(30分)**:
31 | - 文章结构是否清晰、层次分明
32 | - 论证是否充分、有理有据
33 | - 段落衔接是否自然流畅
34 | - 是否存在跳跃式思维或逻辑漏洞
35 |
36 | 3. **原创性(20分)**:
37 | - 是否有独特见解和深度分析
38 | - 是否是简单资料堆砌
39 | - 案例是否具有实战价值
40 | - 是否避免空洞套话
41 |
42 | 4. **规范性(10分)**:
43 | - Markdown格式是否规范
44 | - 代码块是否正确标注语言
45 | - 中英文标点是否符合规范
46 | - 专业术语使用是否统一
47 |
48 | **输出格式(严格按照JSON格式,不要添加任何其他文字):**
49 |
50 | ```json
51 | {
52 | ""overallScore"": 85,
53 | ""accuracy"": {
54 | ""score"": 38,
55 | ""issues"": [""问题描述1"", ""问题描述2""]
56 | },
57 | ""logic"": {
58 | ""score"": 25,
59 | ""issues"": [""问题描述1""]
60 | },
61 | ""originality"": {
62 | ""score"": 18,
63 | ""issues"": []
64 | },
65 | ""formatting"": {
66 | ""score"": 9,
67 | ""issues"": [""问题描述1""]
68 | },
69 | ""recommendation"": ""通过"",
70 | ""summary"": ""总体评价和具体修改建议""
71 | }
72 | ```
73 |
74 | **评分规则:**
75 | - 总分 ≥ 80分: recommendation为""通过""
76 | - 70 ≤ 总分 < 80: recommendation为""需修改""
77 | - 总分 < 70: recommendation为""不通过""
78 |
79 | **注意事项:**
80 | - 评分要客观公正,不要过于严苛或宽松
81 | - issues数组中的每个问题要具体明确,指出位置
82 | - summary要给出可操作的修改建议
83 | - 必须严格按照JSON格式输出,不要有多余文字";
84 |
85 | protected override float Temperature => 0.3f; // 降低温度以提高输出稳定性
86 |
87 | public ReviewerAgent(
88 | ILogger logger,
89 | AgentExecutionRepository executionRepository,
90 | McpConfigService mcpConfigService)
91 | : base(logger, executionRepository, mcpConfigService)
92 | {
93 | }
94 |
95 | ///
96 | /// 执行质量审查任务
97 | ///
98 | /// 博客标题
99 | /// 博客内容
100 | /// 任务ID
101 | /// 审查结果
102 | public async Task ReviewAsync(string title, string content, int taskId)
103 | {
104 | var input = $@"请审查以下博客文章:
105 |
106 | **标题:** {title}
107 |
108 | **内容:**
109 | {content}
110 |
111 | 请严格按照JSON格式输出审查结果,不要添加任何解释性文字。";
112 |
113 | var output = await ExecuteAsync(input, taskId);
114 |
115 | // 解析JSON响应
116 | var result = ParseJsonResponse(output);
117 |
118 | if (result == null)
119 | {
120 | _logger.LogWarning($"[{AgentName}] JSON解析失败,返回默认审查结果");
121 |
122 | // 返回默认的低分结果
123 | return new ReviewResultDto
124 | {
125 | OverallScore = 50,
126 | Accuracy = new DimensionScore { Score = 20, Issues = new List { "AI响应格式错误,无法准确评估" } },
127 | Logic = new DimensionScore { Score = 15, Issues = new List() },
128 | Originality = new DimensionScore { Score = 10, Issues = new List() },
129 | Formatting = new DimensionScore { Score = 5, Issues = new List() },
130 | Recommendation = "需修改",
131 | Summary = "审查结果解析失败,建议人工检查文章质量"
132 | };
133 | }
134 |
135 | return result;
136 | }
137 | }
138 | }
139 |
140 |
--------------------------------------------------------------------------------
/BlogAgent/Components/GlobalHeader/RightContent.razor.cs:
--------------------------------------------------------------------------------
1 | using AntDesign;
2 | using AntDesign.ProLayout;
3 | using Microsoft.AspNetCore.Components;
4 | using BlogAgent.Models;
5 |
6 | namespace BlogAgent.Components
7 | {
8 | public partial class RightContent
9 | {
10 | private CurrentUser _currentUser = new CurrentUser();
11 | private NoticeIconData[] _notifications = { };
12 | private NoticeIconData[] _messages = { };
13 | private NoticeIconData[] _events = { };
14 | private int _count = 0;
15 |
16 | private List> DefaultOptions { get; set; } = new List>
17 | {
18 | new AutoCompleteDataItem
19 | {
20 | Label = "umi ui",
21 | Value = "umi ui"
22 | },
23 | new AutoCompleteDataItem
24 | {
25 | Label = "Pro Table",
26 | Value = "Pro Table"
27 | },
28 | new AutoCompleteDataItem
29 | {
30 | Label = "Pro Layout",
31 | Value = "Pro Layout"
32 | }
33 | };
34 |
35 | public AvatarMenuItem[] AvatarMenuItems { get; set; } = new AvatarMenuItem[]
36 | {
37 | new() { Key = "center", IconType = "user", Option = "个人中心"},
38 | new() { Key = "setting", IconType = "setting", Option = "个人设置"},
39 | new() { IsDivider = true },
40 | new() { Key = "logout", IconType = "logout", Option = "退出登录"}
41 | };
42 |
43 | [Inject] protected NavigationManager NavigationManager { get; set; }
44 |
45 | [Inject] protected MessageService MessageService { get; set; }
46 |
47 | protected override async Task OnInitializedAsync()
48 | {
49 | await base.OnInitializedAsync();
50 | SetClassMap();
51 |
52 | }
53 |
54 | ///
55 | /// 设置组件的CSS类映射
56 | ///
57 | protected void SetClassMap()
58 | {
59 | ClassMapper
60 | .Clear()
61 | .Add("right");
62 | }
63 |
64 | ///
65 | /// 处理用户菜单项选择事件
66 | ///
67 | /// 选中的菜单项
68 | public void HandleSelectUser(MenuItem item)
69 | {
70 | switch (item.Key)
71 | {
72 | case "center":
73 | NavigationManager.NavigateTo("/account/center");
74 | break;
75 | case "setting":
76 | NavigationManager.NavigateTo("/account/settings");
77 | break;
78 | case "logout":
79 | NavigationManager.NavigateTo("/user/login");
80 | break;
81 | }
82 | }
83 |
84 | ///
85 | /// 处理语言选择菜单项事件
86 | ///
87 | /// 选中的语言菜单项
88 | public void HandleSelectLang(MenuItem item)
89 | {
90 | }
91 |
92 | ///
93 | /// 处理清空通知、消息或事件列表的事件
94 | ///
95 | /// 要清空的项目类型(notification/message/event)
96 | /// 异步任务
97 | public async Task HandleClear(string key)
98 | {
99 | switch (key)
100 | {
101 | case "notification":
102 | _notifications = new NoticeIconData[] { };
103 | break;
104 | case "message":
105 | _messages = new NoticeIconData[] { };
106 | break;
107 | case "event":
108 | _events = new NoticeIconData[] { };
109 | break;
110 | }
111 | MessageService.Success($"清空了{key}");
112 | }
113 |
114 | ///
115 | /// 处理查看更多的事件
116 | ///
117 | /// 要查看更多的项目类型
118 | /// 异步任务
119 | public async Task HandleViewMore(string key)
120 | {
121 | MessageService.Info("Click on view more");
122 | }
123 | }
124 | }
--------------------------------------------------------------------------------
/BlogAgent/wwwroot/css/site.css:
--------------------------------------------------------------------------------
1 | /* stylelint-disable at-rule-empty-line-before,at-rule-name-space-after,at-rule-no-unknown */
2 | /* stylelint-disable no-duplicate-selectors */
3 | /* stylelint-disable */
4 | /* stylelint-disable declaration-bang-space-before,no-duplicate-selectors,string-no-newline */
5 | html,
6 | body,
7 | #root,
8 | #app,
9 | app {
10 | height: 100%;
11 | }
12 | .colorWeak {
13 | filter: invert(80%);
14 | }
15 | .ant-layout {
16 | min-height: 100vh;
17 | }
18 | canvas {
19 | display: block;
20 | }
21 | body {
22 | text-rendering: optimizeLegibility;
23 | -webkit-font-smoothing: antialiased;
24 | -moz-osx-font-smoothing: grayscale;
25 | }
26 | ul,
27 | ol {
28 | list-style: none;
29 | }
30 | .action {
31 | cursor: pointer;
32 | }
33 | @media (max-width: 480px) {
34 | .ant-table {
35 | width: 100%;
36 | overflow-x: auto;
37 | }
38 | .ant-table-thead > tr > th,
39 | .ant-table-tbody > tr > th,
40 | .ant-table-thead > tr > td,
41 | .ant-table-tbody > tr > td {
42 | white-space: pre;
43 | }
44 | .ant-table-thead > tr > th > span,
45 | .ant-table-tbody > tr > th > span,
46 | .ant-table-thead > tr > td > span,
47 | .ant-table-tbody > tr > td > span {
48 | display: block;
49 | }
50 | }
51 | @media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
52 | body .ant-design-pro > .ant-layout {
53 | min-height: 100vh;
54 | }
55 | }
56 |
57 |
58 |
59 | ::-webkit-scrollbar {
60 | width: 1px; /* ���ù������Ŀ��� */
61 | height: 8px; /* ����ˮƽ�������ĸ߶� */
62 | }
63 |
64 | ::-webkit-scrollbar-track {
65 | background: #f5f5f5; /* ���ù���������ı���ɫ */
66 | }
67 |
68 | ::-webkit-scrollbar-thumb {
69 | background: #c1c1c1; /* ���ù�����Ĵָ�ı���ɫ�����϶��IJ��֣� */
70 | border-radius: 8px; /* ���ù�����Ĵָ��Բ�� */
71 | }
72 |
73 | ::-webkit-scrollbar-thumb:hover {
74 | background: #555; /* �����ͣʱ������Ĵָ�ı���ɫ */
75 | }
76 |
77 | /* ������Firefox */
78 | * {
79 | scrollbar-width: thin; /* ���ù�����Ϊϸ�� */
80 | scrollbar-color: #ccc #f1f1f1; /* ���ù�����Ĵָ�������ɫ */
81 | }
82 |
83 | /* HTML预览独立工具栏样式 */
84 | .html-preview-toolbar {
85 | position: absolute;
86 | top: 30px;
87 | right: 8px;
88 | z-index: 15;
89 | display: flex;
90 | align-items: center;
91 | gap: 4px;
92 | padding: 4px;
93 | background: rgba(255, 255, 255, 0.95);
94 | border-radius: 6px;
95 | box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
96 | backdrop-filter: blur(4px);
97 | border: 1px solid rgba(127, 127, 255, 0.2);
98 | }
99 |
100 | /* HTML预览按钮样式 */
101 | .html-preview-btn {
102 | background: linear-gradient(135deg, #7F7FFF 0%, #9F9FFF 100%);
103 | color: white;
104 | border: none;
105 | border-radius: 4px;
106 | padding: 6px 12px;
107 | font-size: 12px;
108 | font-weight: 500;
109 | cursor: pointer;
110 | transition: all 0.3s ease;
111 | outline: none;
112 | box-shadow: 0 1px 3px rgba(127, 127, 255, 0.3);
113 | }
114 |
115 | .html-preview-btn:hover {
116 | background: linear-gradient(135deg, #6F6FFF 0%, #8F8FFF 100%);
117 | transform: translateY(-1px);
118 | box-shadow: 0 3px 12px rgba(127, 127, 255, 0.4);
119 | }
120 |
121 | .html-preview-btn:active {
122 | transform: translateY(0);
123 | box-shadow: 0 1px 4px rgba(127, 127, 255, 0.3);
124 | }
125 |
126 | .html-preview-btn:focus {
127 | box-shadow: 0 0 0 3px rgba(127, 127, 255, 0.3);
128 | }
129 |
130 | /* 代码块容器样式优化 */
131 | pre[class*="language-"] {
132 | position: relative;
133 | }
134 |
135 | /* 原始toolbar样式保持不变 */
136 | pre[class*="language-"] .toolbar {
137 | position: absolute;
138 | top: 8px;
139 | right: 8px;
140 | z-index: 10;
141 | display: flex;
142 | align-items: center;
143 | gap: 4px;
144 | padding: 4px;
145 | background: rgba(255, 255, 255, 0.9);
146 | border-radius: 4px;
147 | box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
148 | }
149 |
150 | /* 响应式设计 */
151 | @media (max-width: 768px) {
152 | .html-preview-btn {
153 | padding: 4px 8px;
154 | font-size: 11px;
155 | }
156 |
157 | .html-preview-toolbar {
158 | gap: 2px;
159 | padding: 2px;
160 | }
161 |
162 | /* 移动端时调整位置 */
163 | .html-preview-toolbar {
164 | top: 30px;
165 | }
166 | }
167 |
168 | @media (max-width: 480px) {
169 | .html-preview-toolbar {
170 | position: static;
171 | margin-top: 8px;
172 | margin-bottom: 8px;
173 | justify-content: center;
174 | background: rgba(255, 255, 255, 0.98);
175 | }
176 |
177 | pre[class*="language-"] .toolbar ~ .html-preview-toolbar {
178 | top: auto;
179 | }
180 | }
--------------------------------------------------------------------------------
/BlogAgent/Pages/Index.razor:
--------------------------------------------------------------------------------
1 | @namespace BlogAgent.Pages
2 | @page "/"
3 | @using BlogAgent.Domain.Services
4 | @using BlogAgent.Domain.Repositories
5 | @using BlogAgent.Domain.Domain.Enum
6 | @inject BlogService BlogService
7 | @inject ReviewResultRepository ReviewResultRepository
8 | @inject NavigationManager NavigationManager
9 | @implements IDisposable
10 |
11 |
12 |
13 | 基于Microsoft Agent Framework的多Agent协作博客生成系统
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 | 资料收集Agent
46 | 智能提取和整理参考资料,生成结构化摘要
47 |
48 |
49 | 博客撰写Agent
50 | 基于资料生成高质量技术博客,支持自定义风格
51 |
52 |
53 | 质量审查Agent
54 | 多维度评估文章质量,提供详细改进建议
55 |
56 |
57 | 工作流编排
58 | 半自动化流程,每阶段用户确认后继续
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
78 |
79 |
80 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | @code {
90 | private int totalTasks = 0;
91 | private int publishedCount = 0;
92 | private int averageScore = 0;
93 | private double passRate = 0;
94 | private bool _disposed = false;
95 |
96 | protected override async Task OnInitializedAsync()
97 | {
98 | try
99 | {
100 | var tasks = await BlogService.GetTaskListAsync(1000);
101 |
102 | if (_disposed) return;
103 |
104 | totalTasks = tasks.Count;
105 | publishedCount = tasks.Count(t => t.Status == AgentTaskStatus.Published);
106 |
107 | var scores = await ReviewResultRepository.GetAverageScoresAsync();
108 |
109 | if (_disposed) return;
110 |
111 | if (scores.ContainsKey("Overall"))
112 | {
113 | averageScore = (int)scores["Overall"];
114 | }
115 |
116 | passRate = await ReviewResultRepository.GetPassRateAsync();
117 | passRate = Math.Round(passRate, 1);
118 |
119 | await SafeStateHasChangedAsync();
120 | }
121 | catch
122 | {
123 | // 忽略错误,使用默认值
124 | }
125 | }
126 |
127 | private void NavigateToCreate()
128 | {
129 | NavigationManager.NavigateTo("/blog/create");
130 | }
131 |
132 | private void NavigateToList()
133 | {
134 | NavigationManager.NavigateTo("/blog/list");
135 | }
136 |
137 | private async Task SafeStateHasChangedAsync()
138 | {
139 | if (!_disposed)
140 | {
141 | try
142 | {
143 | await InvokeAsync(StateHasChanged);
144 | }
145 | catch (ObjectDisposedException)
146 | {
147 | // 组件已被销毁,忽略此异常
148 | }
149 | }
150 | }
151 |
152 | public void Dispose()
153 | {
154 | _disposed = true;
155 | }
156 | }
157 |
--------------------------------------------------------------------------------
/BlogAgent.Domain/Services/WebContentService.cs:
--------------------------------------------------------------------------------
1 | using BlogAgent.Domain.Common.Extensions;
2 | using Microsoft.Extensions.Logging;
3 | using System.Net;
4 | using System.Text;
5 | using System.Text.RegularExpressions;
6 |
7 | namespace BlogAgent.Domain.Services
8 | {
9 | ///
10 | /// Web 内容抓取服务
11 | ///
12 | [ServiceDescription(typeof(WebContentService), Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped)]
13 | public class WebContentService
14 | {
15 | private readonly ILogger _logger;
16 | private readonly HttpClient _httpClient;
17 |
18 | public WebContentService(ILogger logger, IHttpClientFactory httpClientFactory)
19 | {
20 | _logger = logger;
21 | _httpClient = httpClientFactory.CreateClient("WebContentFetcher");
22 | _httpClient.Timeout = TimeSpan.FromSeconds(30);
23 | _httpClient.DefaultRequestHeaders.Add("User-Agent", "BlogAgent/1.0 (Content Fetcher)");
24 | }
25 |
26 | ///
27 | /// 抓取 URL 内容
28 | ///
29 | /// 目标 URL
30 | /// 清洗后的文本内容
31 | public async Task FetchUrlContentAsync(string url)
32 | {
33 | try
34 | {
35 | _logger.LogInformation($"开始抓取 URL: {url}");
36 |
37 | var response = await _httpClient.GetAsync(url);
38 | response.EnsureSuccessStatusCode();
39 |
40 | var content = await response.Content.ReadAsStringAsync();
41 | var contentType = response.Content.Headers.ContentType?.MediaType ?? "";
42 |
43 | // 根据内容类型处理
44 | string textContent;
45 | if (contentType.Contains("text/html"))
46 | {
47 | textContent = ExtractTextFromHtml(content);
48 | }
49 | else if (contentType.Contains("text/plain"))
50 | {
51 | textContent = content;
52 | }
53 | else if (contentType.Contains("application/json"))
54 | {
55 | textContent = content;
56 | }
57 | else
58 | {
59 | textContent = content; // 其他类型直接返回
60 | }
61 |
62 | _logger.LogInformation($"URL 抓取成功: {url}, 内容长度: {textContent.Length}");
63 | return textContent;
64 | }
65 | catch (HttpRequestException ex)
66 | {
67 | _logger.LogError(ex, $"HTTP 请求失败: {url}");
68 | return $"[无法访问 URL: {url}]\n错误: {ex.Message}";
69 | }
70 | catch (TaskCanceledException ex)
71 | {
72 | _logger.LogError(ex, $"请求超时: {url}");
73 | return $"[URL 访问超时: {url}]";
74 | }
75 | catch (Exception ex)
76 | {
77 | _logger.LogError(ex, $"抓取 URL 失败: {url}");
78 | return $"[URL 抓取失败: {url}]\n错误: {ex.Message}";
79 | }
80 | }
81 |
82 | ///
83 | /// 批量抓取 URL 内容
84 | ///
85 | /// URL 列表
86 | /// 格式化的内容集合
87 | public async Task FetchMultipleUrlsAsync(IEnumerable urls)
88 | {
89 | var fetchedContents = new List();
90 |
91 | foreach (var url in urls)
92 | {
93 | var trimmedUrl = url.Trim();
94 | if (string.IsNullOrWhiteSpace(trimmedUrl))
95 | continue;
96 |
97 | var content = await FetchUrlContentAsync(trimmedUrl);
98 | var formattedContent = $@"
99 | ================================================================================
100 | 📄 来源: {trimmedUrl}
101 | ================================================================================
102 |
103 | {content}
104 |
105 | ";
106 | fetchedContents.Add(formattedContent);
107 | }
108 |
109 | if (fetchedContents.Count == 0)
110 | {
111 | return "无可用的参考资料";
112 | }
113 |
114 | return string.Join("\n", fetchedContents);
115 | }
116 |
117 | ///
118 | /// 从 HTML 中提取纯文本内容
119 | ///
120 | private string ExtractTextFromHtml(string html)
121 | {
122 | if (string.IsNullOrWhiteSpace(html))
123 | return string.Empty;
124 |
125 | try
126 | {
127 | // 移除 script 和 style 标签
128 | html = Regex.Replace(html, @"", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
129 | html = Regex.Replace(html, @"", "", RegexOptions.Singleline | RegexOptions.IgnoreCase);
130 |
131 | // 保留代码块(pre, code)的换行
132 | html = Regex.Replace(html, @"]*?>(.*?)
", "\n```\n$1\n```\n", RegexOptions.Singleline | RegexOptions.IgnoreCase);
133 | html = Regex.Replace(html, @"]*?>(.*?)", "`$1`", RegexOptions.Singleline | RegexOptions.IgnoreCase);
134 |
135 | // 将常见块级元素转换为换行
136 | html = Regex.Replace(html, @"<(p|div|br|h[1-6]|li|tr)[^>]*?>", "\n", RegexOptions.IgnoreCase);
137 | html = Regex.Replace(html, @"(p|div|h[1-6]|li|tr)>", "\n", RegexOptions.IgnoreCase);
138 |
139 | // 移除所有其他 HTML 标签
140 | html = Regex.Replace(html, @"<[^>]+>", "");
141 |
142 | // 解码 HTML 实体
143 | html = WebUtility.HtmlDecode(html);
144 |
145 | // 清理多余空白
146 | html = Regex.Replace(html, @"[ \t]+", " "); // 多个空格/制表符 -> 单个空格
147 | html = Regex.Replace(html, @"\n\s*\n\s*\n+", "\n\n"); // 多个换行 -> 双换行
148 | html = html.Trim();
149 |
150 | // 限制内容长度(避免过长)
151 | const int MaxLength = 50000;
152 | if (html.Length > MaxLength)
153 | {
154 | html = html.Substring(0, MaxLength) + "\n\n[内容过长,已截断...]";
155 | }
156 |
157 | return html;
158 | }
159 | catch (Exception ex)
160 | {
161 | _logger.LogError(ex, "HTML 文本提取失败");
162 | return html; // 失败时返回原始内容
163 | }
164 | }
165 |
166 | ///
167 | /// 验证 URL 格式
168 | ///
169 | public static bool IsValidUrl(string url)
170 | {
171 | if (string.IsNullOrWhiteSpace(url))
172 | return false;
173 |
174 | return Uri.TryCreate(url, UriKind.Absolute, out var uriResult)
175 | && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
176 | }
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/BlogAgent/Pages/Blog/List.razor:
--------------------------------------------------------------------------------
1 | @page "/blog/list"
2 | @using BlogAgent.Domain.Domain.Dto
3 | @using AgentTaskStatus = BlogAgent.Domain.Domain.Enum.AgentTaskStatus
4 | @using BlogAgent.Domain.Services
5 | @inject BlogService BlogService
6 | @inject NavigationManager Navigation
7 | @inject IMessageService Message
8 | @inject ModalService ModalService
9 | @implements IDisposable
10 |
11 |
12 |
13 |
14 |
15 |
18 |
19 |
20 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
34 |
35 |
36 |
37 | @{
38 | var (color, text) = GetStatusDisplay(context.Status);
39 | }
40 | @text
41 |
42 |
43 | @if (!string.IsNullOrEmpty(context.CurrentStage))
44 | {
45 | @GetStageText(context.CurrentStage)
46 | }
47 | else
48 | {
49 | -
50 | }
51 |
52 |
53 | @context.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
54 |
55 |
56 |
57 |
58 |
61 |
62 | @if (context.Status != AgentTaskStatus.Published)
63 | {
64 |
65 |
68 |
69 | }
70 |
71 |
75 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 | @code {
86 | private List tasks = new();
87 | private bool loading = false;
88 | private bool _disposed = false;
89 |
90 | protected override async Task OnInitializedAsync()
91 | {
92 | await LoadData();
93 | }
94 |
95 | private async Task LoadData()
96 | {
97 | loading = true;
98 | await SafeStateHasChangedAsync();
99 |
100 | try
101 | {
102 | tasks = await BlogService.GetTaskListAsync(50);
103 |
104 | if (_disposed) return;
105 | }
106 | catch (Exception ex)
107 | {
108 | if (!_disposed)
109 | {
110 | await InvokeAsync(() => Message.Error($"加载数据失败: {ex.Message}"));
111 | }
112 | }
113 | finally
114 | {
115 | if (!_disposed)
116 | {
117 | loading = false;
118 | await SafeStateHasChangedAsync();
119 | }
120 | }
121 | }
122 |
123 | private async Task DeleteTask(int taskId)
124 | {
125 | try
126 | {
127 | var success = await BlogService.DeleteTaskAsync(taskId);
128 |
129 | if (_disposed) return;
130 |
131 | if (success)
132 | {
133 | await InvokeAsync(() => Message.Success("删除成功"));
134 | await LoadData();
135 | }
136 | else
137 | {
138 | await InvokeAsync(() => Message.Error("删除失败"));
139 | }
140 | }
141 | catch (Exception ex)
142 | {
143 | if (!_disposed)
144 | {
145 | await InvokeAsync(() => Message.Error($"删除失败: {ex.Message}"));
146 | }
147 | }
148 | }
149 |
150 | private async Task SafeStateHasChangedAsync()
151 | {
152 | if (!_disposed)
153 | {
154 | try
155 | {
156 | await InvokeAsync(StateHasChanged);
157 | }
158 | catch (ObjectDisposedException)
159 | {
160 | // 组件已被销毁,忽略此异常
161 | }
162 | }
163 | }
164 |
165 | public void Dispose()
166 | {
167 | _disposed = true;
168 | }
169 |
170 | private (string color, string text) GetStatusDisplay(AgentTaskStatus status)
171 | {
172 | return status switch
173 | {
174 | AgentTaskStatus.Created => ("default", "已创建"),
175 | AgentTaskStatus.Researching => ("processing", "资料收集中"),
176 | AgentTaskStatus.ResearchCompleted => ("cyan", "资料收集完成"),
177 | AgentTaskStatus.Writing => ("processing", "撰写中"),
178 | AgentTaskStatus.WritingCompleted => ("blue", "撰写完成"),
179 | AgentTaskStatus.Reviewing => ("processing", "审查中"),
180 | AgentTaskStatus.ReviewCompleted => ("orange", "审查完成"),
181 | AgentTaskStatus.Published => ("success", "已发布"),
182 | AgentTaskStatus.Failed => ("error", "失败"),
183 | _ => ("default", "未知")
184 | };
185 | }
186 |
187 | private string GetStageText(string stage)
188 | {
189 | return stage switch
190 | {
191 | "created" => "已创建",
192 | "research" => "资料收集",
193 | "research_completed" => "资料收集完成",
194 | "write" => "博客撰写",
195 | "write_completed" => "撰写完成",
196 | "review" => "质量审查",
197 | "review_completed" => "审查完成",
198 | "published" => "已发布",
199 | _ => stage
200 | };
201 | }
202 | }
203 |
204 |
--------------------------------------------------------------------------------
/BlogAgent/Pages/Blog/Detail.razor:
--------------------------------------------------------------------------------
1 | @page "/blog/detail/{TaskId:int}"
2 | @using BlogAgent.Domain.Domain.Model
3 | @using BlogAgent.Domain.Domain.Dto
4 | @using BlogAgent.Domain.Services
5 | @inject BlogService BlogService
6 | @inject NavigationManager Navigation
7 | @inject IMessageService Message
8 |
9 |
10 |
11 |
12 | @if (content != null && !content.IsPublished)
13 | {
14 |
15 |
18 |
19 | }
20 |
21 |
24 |
25 | @if (content != null)
26 | {
27 |
28 |
31 |
32 | }
33 |
34 |
35 |
36 |
37 | @if (loading)
38 | {
39 |
40 |
41 |
42 |
43 |
44 | }
45 | else if (content != null)
46 | {
47 |
48 |
49 |
50 | @content.Title
51 |
52 |
53 | @if (content.IsPublished)
54 | {
55 | 已发布
56 | }
57 | else
58 | {
59 | 草稿
60 | }
61 |
62 |
63 | @content.WordCount 字
64 |
65 |
66 | @content.CreatedAt.ToString("yyyy-MM-dd HH:mm:ss")
67 |
68 |
69 | @(content.PublishedAt?.ToString("yyyy-MM-dd HH:mm:ss") ?? "-")
70 |
71 |
72 |
73 | @if (reviewResult != null)
74 | {
75 |
76 |
77 |
80 |
81 | @reviewResult.Accuracy.Score / 40
82 | @reviewResult.Logic.Score / 30
83 | @reviewResult.Originality.Score / 20
84 | @reviewResult.Formatting.Score / 10
85 |
86 |
87 | @reviewResult.Recommendation
88 |
89 |
90 | @if (!string.IsNullOrEmpty(reviewResult.Summary))
91 | {
92 |
93 | @reviewResult.Summary
94 |
95 | }
96 |
97 | }
98 |
99 |
100 | 博客内容
101 |
102 |
103 |
104 |
105 |
106 |
107 | }
108 | else
109 | {
110 |
111 |
112 |
115 |
116 |
117 | }
118 |
119 | @code {
120 | [Parameter] public int TaskId { get; set; }
121 |
122 | private bool loading = false;
123 | private bool publishing = false;
124 | private bool exporting = false;
125 | private BlogContent? content;
126 | private ReviewResultDto? reviewResult;
127 |
128 | protected override async Task OnInitializedAsync()
129 | {
130 | await LoadData();
131 | }
132 |
133 | private async Task LoadData()
134 | {
135 | loading = true;
136 | try
137 | {
138 | content = await BlogService.GetContentAsync(TaskId);
139 |
140 | if (content != null)
141 | {
142 | reviewResult = await BlogService.GetReviewResultAsync(TaskId);
143 | }
144 | }
145 | catch (Exception ex)
146 | {
147 | Message.Error($"加载数据失败: {ex.Message}");
148 | }
149 | finally
150 | {
151 | loading = false;
152 | }
153 | }
154 |
155 | private async Task PublishBlog()
156 | {
157 | publishing = true;
158 | try
159 | {
160 | var success = await BlogService.PublishBlogAsync(TaskId);
161 |
162 | if (success)
163 | {
164 | Message.Success("发布成功!");
165 | await LoadData();
166 | }
167 | else
168 | {
169 | Message.Error("发布失败");
170 | }
171 | }
172 | catch (Exception ex)
173 | {
174 | Message.Error($"发布失败: {ex.Message}");
175 | }
176 | finally
177 | {
178 | publishing = false;
179 | }
180 | }
181 |
182 | private async Task ExportMarkdown()
183 | {
184 | exporting = true;
185 | try
186 | {
187 | // 使用应用根目录的exports文件夹
188 | var exportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exports");
189 | var filePath = await BlogService.ExportToMarkdownAsync(TaskId, exportPath);
190 |
191 | Message.Success($"导出成功: {Path.GetFileName(filePath)}");
192 | }
193 | catch (Exception ex)
194 | {
195 | Message.Error($"导出失败: {ex.Message}");
196 | }
197 | finally
198 | {
199 | exporting = false;
200 | }
201 | }
202 | }
203 |
204 |
--------------------------------------------------------------------------------
/BlogAgent.Domain/Services/Agents/ResearcherAgent.cs:
--------------------------------------------------------------------------------
1 | using BlogAgent.Domain.Services.Agents.Base;
2 | using BlogAgent.Domain.Common.Extensions;
3 | using BlogAgent.Domain.Domain.Dto;
4 | using BlogAgent.Domain.Domain.Enum;
5 | using BlogAgent.Domain.Domain.Model;
6 | using BlogAgent.Domain.Repositories;
7 | using Microsoft.Extensions.Logging;
8 | using Microsoft.Extensions.AI;
9 | using System.Text.Json;
10 | using System.ComponentModel;
11 |
12 | namespace BlogAgent.Domain.Services.Agents
13 | {
14 | ///
15 | /// 资料收集专家Agent - 使用 Agent Framework
16 | ///
17 | [ServiceDescription(typeof(ResearcherAgent), Microsoft.Extensions.DependencyInjection.ServiceLifetime.Scoped)]
18 | public class ResearcherAgent : BaseAgentService
19 | {
20 | public override string AgentName => "资料收集专家";
21 |
22 | public override AgentType AgentType => AgentType.Researcher;
23 |
24 | protected override string Instructions => @"你是一位专业的技术资料收集专家。
25 |
26 | **任务:**
27 | 1. 仔细阅读用户提供的主题和参考资料
28 | 2. 提取关键信息点(技术概念、代码示例、最佳实践、应用场景等)
29 | 3. 整理成结构化的JSON格式输出
30 |
31 | **输出要求:**
32 | - topic_analysis: 对主题的理解和定位,包括技术背景、适用场景、目标读者
33 | - key_points: 核心要点列表,每个要点包含重要程度(1-3,3最高)和内容
34 | - technical_details: 技术细节列表,每个包含标题和详细说明
35 | - code_examples: 代码示例列表(如果有),包含语言、代码和描述
36 | - references: 参考来源列表
37 |
38 | **质量要求:**
39 | - 信息准确,不添加未提供的内容
40 | - 结构清晰,层次分明
41 | - 提炼核心概念,避免冗余
42 | - 如果资料不足,明确指出缺失的部分";
43 |
44 | // 使用结构化输出
45 | protected override ChatResponseFormat? ResponseFormat =>
46 | ChatResponseFormat.ForJsonSchema(schemaName: "ResearchOutput");
47 |
48 | // 添加工具函数
49 | protected override IEnumerable? Tools => new[]
50 | {
51 | Microsoft.Extensions.AI.AIFunctionFactory.Create(CountWordsInText),
52 | Microsoft.Extensions.AI.AIFunctionFactory.Create(ExtractCodeBlocks)
53 | };
54 |
55 | public ResearcherAgent(
56 | ILogger logger,
57 | AgentExecutionRepository executionRepository,
58 | McpConfigService mcpConfigService)
59 | : base(logger, executionRepository, mcpConfigService)
60 | {
61 | }
62 |
63 | ///
64 | /// 执行资料收集任务
65 | ///
66 | /// 博客主题
67 | /// 参考资料
68 | /// 任务ID
69 | /// 资料收集结果
70 | public async Task ResearchAsync(string topic, string referenceContent, int taskId)
71 | {
72 | var input = $@"**主题:** {topic}
73 |
74 | **参考资料:**
75 | {referenceContent}
76 |
77 | 请按照指示整理资料,输出结构化的JSON格式数据。";
78 |
79 | var output = await ExecuteAsync(input, taskId);
80 |
81 | // 解析结构化输出
82 | var researchOutput = JsonSerializer.Deserialize(output);
83 |
84 | if (researchOutput == null)
85 | {
86 | throw new InvalidOperationException("无法解析研究结果");
87 | }
88 |
89 | // 转换为 Markdown 格式(保持向后兼容)
90 | var markdown = ConvertToMarkdown(researchOutput);
91 |
92 | return new ResearchResultDto
93 | {
94 | Summary = markdown,
95 | KeyPoints = researchOutput.KeyPoints.Select(kp => kp.Content).ToList(),
96 | Timestamp = DateTime.Now
97 | };
98 | }
99 |
100 | ///
101 | /// 将结构化输出转换为 Markdown 格式
102 | ///
103 | private string ConvertToMarkdown(ResearchOutput output)
104 | {
105 | var markdown = new System.Text.StringBuilder();
106 |
107 | markdown.AppendLine("## 主题分析");
108 | markdown.AppendLine(output.TopicAnalysis);
109 | markdown.AppendLine();
110 |
111 | markdown.AppendLine("## 核心要点");
112 | foreach (var point in output.KeyPoints.OrderByDescending(p => p.Importance))
113 | {
114 | var stars = new string('⭐', point.Importance);
115 | markdown.AppendLine($"{stars} {point.Content}");
116 | }
117 | markdown.AppendLine();
118 |
119 | markdown.AppendLine("## 技术细节");
120 | foreach (var detail in output.TechnicalDetails)
121 | {
122 | markdown.AppendLine($"### {detail.Title}");
123 | markdown.AppendLine(detail.Description);
124 | markdown.AppendLine();
125 | }
126 |
127 | if (output.CodeExamples.Any())
128 | {
129 | markdown.AppendLine("## 代码示例");
130 | foreach (var example in output.CodeExamples)
131 | {
132 | markdown.AppendLine($"```{example.Language}");
133 | markdown.AppendLine(example.Code);
134 | markdown.AppendLine("```");
135 | markdown.AppendLine(example.Description);
136 | markdown.AppendLine();
137 | }
138 | }
139 |
140 | markdown.AppendLine("## 参考来源");
141 | foreach (var reference in output.References)
142 | {
143 | markdown.AppendLine($"- {reference}");
144 | }
145 |
146 | return markdown.ToString();
147 | }
148 |
149 | // ============ Agent Tools ============
150 |
151 | ///
152 | /// 工具函数: 统计文本字数
153 | ///
154 | [Description("统计给定文本的字数,包括中文字符和英文单词")]
155 | private static int CountWordsInText([Description("要统计的文本内容")] string text)
156 | {
157 | if (string.IsNullOrWhiteSpace(text))
158 | return 0;
159 |
160 | int chineseChars = text.Count(c => c >= 0x4E00 && c <= 0x9FA5);
161 | int englishWords = text.Split(new[] { ' ', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)
162 | .Count(word => word.Any(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')));
163 |
164 | return chineseChars + englishWords;
165 | }
166 |
167 | ///
168 | /// 工具函数: 提取代码块
169 | ///
170 | [Description("从Markdown文本中提取所有代码块")]
171 | private static string ExtractCodeBlocks([Description("Markdown格式的文本")] string markdown)
172 | {
173 | var codeBlocks = new List();
174 | var lines = markdown.Split('\n');
175 | bool inCodeBlock = false;
176 | var currentBlock = new System.Text.StringBuilder();
177 |
178 | foreach (var line in lines)
179 | {
180 | if (line.Trim().StartsWith("```"))
181 | {
182 | if (inCodeBlock)
183 | {
184 | codeBlocks.Add(currentBlock.ToString());
185 | currentBlock.Clear();
186 | inCodeBlock = false;
187 | }
188 | else
189 | {
190 | inCodeBlock = true;
191 | }
192 | }
193 | else if (inCodeBlock)
194 | {
195 | currentBlock.AppendLine(line);
196 | }
197 | }
198 |
199 | return string.Join("\n---\n", codeBlocks);
200 | }
201 | }
202 | }
203 |
204 |
205 |
--------------------------------------------------------------------------------
/BlogAgent.Domain/Utils/ConvertUtils.cs:
--------------------------------------------------------------------------------
1 | using Newtonsoft.Json;
2 |
3 | namespace BlogAgent.Domain
4 | {
5 | ///
6 | /// 转换工具类
7 | ///
8 | public static class ConvertUtils
9 | {
10 | ///
11 | /// 判断是否为空,为空返回true
12 | ///
13 | ///
14 | ///
15 | public static bool IsNull(this object data)
16 | {
17 | //如果为null
18 | if (data == null)
19 | {
20 | return true;
21 | }
22 |
23 | //如果为""
24 | if (data.GetType() == typeof(String))
25 | {
26 | if (string.IsNullOrEmpty(data.ToString().Trim()))
27 | {
28 | return true;
29 | }
30 | }
31 | return false;
32 | }
33 |
34 | ///
35 | /// 判断是否为空,为空返回true
36 | ///
37 | ///
38 | ///
39 | public static bool IsNotNull(this object data)
40 | {
41 | //如果为null
42 | if (data == null)
43 | {
44 | return false;
45 | }
46 |
47 | //如果为""
48 | if (data.GetType() == typeof(String))
49 | {
50 | if (string.IsNullOrEmpty(data.ToString().Trim()))
51 | {
52 | return false;
53 | }
54 | }
55 | return true;
56 | }
57 |
58 | ///
59 | /// 判断是否为空,为空返回true
60 | ///
61 | ///
62 | ///
63 | public static bool IsNull(string data)
64 | {
65 | //如果为null
66 | if (data == null)
67 | {
68 | return true;
69 | }
70 |
71 | //如果为""
72 | if (data.GetType() == typeof(String))
73 | {
74 | if (string.IsNullOrEmpty(data.ToString().Trim()))
75 | {
76 | return true;
77 | }
78 | }
79 | return false;
80 | }
81 |
82 | ///
83 | /// 将obj类型转换为string
84 | ///
85 | ///
86 | ///
87 | public static string ConvertToString(this object s)
88 | {
89 | if (s == null)
90 | {
91 | return "";
92 | }
93 | else
94 | {
95 | return Convert.ToString(s);
96 | }
97 | }
98 |
99 | ///
100 | /// object 转int32
101 | ///
102 | ///
103 | ///
104 | public static Int32 ConvertToInt32(this object s)
105 | {
106 | int i = 0;
107 | if (s == null)
108 | {
109 | return 0;
110 | }
111 | else
112 | {
113 | int.TryParse(s.ToString(), out i);
114 | }
115 | return i;
116 | }
117 |
118 | ///
119 | /// object 转int32
120 | ///
121 | ///
122 | ///
123 | public static Int64 ConvertToInt64(this object s)
124 | {
125 | long i = 0;
126 | if (s == null)
127 | {
128 | return 0;
129 | }
130 | else
131 | {
132 | long.TryParse(s.ToString(), out i);
133 | }
134 | return i;
135 | }
136 |
137 | ///
138 | /// 将字符串转double
139 | ///
140 | ///
141 | ///
142 | public static double ConvertToDouble(this object s)
143 | {
144 | double i = 0;
145 | if (s == null)
146 | {
147 | return 0;
148 | }
149 | else
150 | {
151 | double.TryParse(s.ToString(), out i);
152 | }
153 | return i;
154 | }
155 |
156 | ///
157 | /// 转换为datetime类型
158 | ///
159 | ///
160 | ///
161 | public static DateTime ConvertToDateTime(this string s)
162 | {
163 | DateTime dt = new DateTime();
164 | if (s == null || s == "")
165 | {
166 | return DateTime.Now;
167 | }
168 | DateTime.TryParse(s, out dt);
169 | return dt;
170 | }
171 |
172 | ///
173 | /// 转换为datetime类型的格式字符串
174 | ///
175 | /// 要转换的对象
176 | /// 格式化字符串
177 | ///
178 | public static string ConvertToDateTime(this string s, string y)
179 | {
180 | DateTime dt = new DateTime();
181 | DateTime.TryParse(s, out dt);
182 | return dt.ToString(y);
183 | }
184 |
185 |
186 | ///
187 | /// 将字符串转换成decimal
188 | ///
189 | ///
190 | ///
191 | public static decimal ConvertToDecimal(this object s)
192 | {
193 | decimal d = 0;
194 | if (s == null || s == "")
195 | {
196 | return 0;
197 | }
198 |
199 | Decimal.TryParse(s.ToString(), out d);
200 |
201 | return d;
202 |
203 | }
204 | ///
205 | /// decimal保留2位小数
206 | ///
207 | public static decimal DecimalFraction(this decimal num)
208 | {
209 | return Convert.ToDecimal(num.ToString("f2"));
210 | }
211 |
212 |
213 | ///
214 | /// 替换html种的特殊字符
215 | ///
216 | ///
217 | ///
218 | public static string ReplaceHtml(this string s)
219 | {
220 | return s.Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"");
221 | }
222 |
223 | ///
224 | /// 流转byte
225 | ///
226 | ///
227 | ///
228 | public static byte[] StreamToByte(this Stream stream)
229 | {
230 | byte[] bytes = new byte[stream.Length];
231 | stream.Read(bytes, 0, bytes.Length);
232 | // 设置当前流的位置为流的开始
233 | stream.Seek(0, SeekOrigin.Begin);
234 | return bytes;
235 | }
236 |
237 | ///
238 | /// \uxxxx转中文,保留换行符号
239 | ///
240 | ///
241 | ///
242 | public static string Unescape(this string value)
243 | {
244 | if (value.IsNull())
245 | {
246 | return "";
247 | }
248 |
249 | try
250 | {
251 | Formatting formatting = Formatting.None;
252 |
253 | object jsonObj = JsonConvert.DeserializeObject(value);
254 | string unescapeValue = JsonConvert.SerializeObject(jsonObj, formatting);
255 | return unescapeValue;
256 | }
257 | catch (Exception ex)
258 | {
259 | Console.WriteLine(ex.ToString());
260 | return "";
261 | }
262 | }
263 |
264 | }
265 | }
266 |
--------------------------------------------------------------------------------
/BlogAgent/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Oo]ut/
33 | [Ll]og/
34 | [Ll]ogs/
35 |
36 | # Visual Studio 2015/2017 cache/options directory
37 | .vs/
38 | # Uncomment if you have tasks that create the project's static files in wwwroot
39 | #wwwroot/
40 |
41 | # Visual Studio 2017 auto generated files
42 | Generated\ Files/
43 |
44 | # MSTest test Results
45 | [Tt]est[Rr]esult*/
46 | [Bb]uild[Ll]og.*
47 |
48 | # NUnit
49 | *.VisualState.xml
50 | TestResult.xml
51 | nunit-*.xml
52 |
53 | # Build Results of an ATL Project
54 | [Dd]ebugPS/
55 | [Rr]eleasePS/
56 | dlldata.c
57 |
58 | # Benchmark Results
59 | BenchmarkDotNet.Artifacts/
60 |
61 | # .NET Core
62 | project.lock.json
63 | project.fragment.lock.json
64 | artifacts/
65 |
66 | # ASP.NET Scaffolding
67 | ScaffoldingReadMe.txt
68 |
69 | # StyleCop
70 | StyleCopReport.xml
71 |
72 | # Files built by Visual Studio
73 | *_i.c
74 | *_p.c
75 | *_h.h
76 | *.ilk
77 | *.meta
78 | *.obj
79 | *.iobj
80 | *.pch
81 | *.pdb
82 | *.ipdb
83 | *.pgc
84 | *.pgd
85 | *.rsp
86 | *.sbr
87 | *.tlb
88 | *.tli
89 | *.tlh
90 | *.tmp
91 | *.tmp_proj
92 | *_wpftmp.csproj
93 | *.log
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio LightSwitch build output
298 | **/*.HTMLClient/GeneratedArtifacts
299 | **/*.DesktopClient/GeneratedArtifacts
300 | **/*.DesktopClient/ModelManifest.xml
301 | **/*.Server/GeneratedArtifacts
302 | **/*.Server/ModelManifest.xml
303 | _Pvt_Extensions
304 |
305 | # Paket dependency manager
306 | .paket/paket.exe
307 | paket-files/
308 |
309 | # FAKE - F# Make
310 | .fake/
311 |
312 | # CodeRush personal settings
313 | .cr/personal
314 |
315 | # Python Tools for Visual Studio (PTVS)
316 | __pycache__/
317 | *.pyc
318 |
319 | # Cake - Uncomment if you are using it
320 | # tools/**
321 | # !tools/packages.config
322 |
323 | # Tabs Studio
324 | *.tss
325 |
326 | # Telerik's JustMock configuration file
327 | *.jmconfig
328 |
329 | # BizTalk build output
330 | *.btp.cs
331 | *.btm.cs
332 | *.odx.cs
333 | *.xsd.cs
334 |
335 | # OpenCover UI analysis results
336 | OpenCover/
337 |
338 | # Azure Stream Analytics local run output
339 | ASALocalRun/
340 |
341 | # MSBuild Binary and Structured Log
342 | *.binlog
343 |
344 | # NVidia Nsight GPU debugger configuration file
345 | *.nvuser
346 |
347 | # MFractors (Xamarin productivity tool) working folder
348 | .mfractor/
349 |
350 | # Local History for Visual Studio
351 | .localhistory/
352 |
353 | # BeatPulse healthcheck temp database
354 | healthchecksdb
355 |
356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
357 | MigrationBackup/
358 |
359 | # Ionide (cross platform F# VS Code tools) working folder
360 | .ionide/
361 |
362 | # Fody - auto-generated XML schema
363 | FodyWeavers.xsd
364 | /BlogAgent/appsettings.Development.json
365 | *.db
366 | /dotnet
367 | /agent-framework
368 | /docs
369 |
--------------------------------------------------------------------------------
/BlogAgent/wwwroot/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | Ant Design Pro Blazor
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
178 |
186 |

187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |

197 | Text2Sql.Net.Web
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
--------------------------------------------------------------------------------
/BlogAgent/Pages/Blog/Create.razor:
--------------------------------------------------------------------------------
1 | @page "/blog/create"
2 | @using BlogAgent.Domain.Domain.Dto
3 | @using BlogAgent.Domain.Services
4 | @inject BlogService BlogService
5 | @inject NavigationManager Navigation
6 | @inject IMessageService Message
7 | @implements IDisposable
8 |
9 |
10 |
11 | 通过AI智能体协作创建高质量技术博客
12 |
13 |
14 |
15 |
16 |
130 |
131 |
132 | @code {
133 | private CreateBlogRequest model = new() { WorkflowMode = "auto" };
134 | private string inputMode = "text";
135 | private bool loading = false;
136 | private string? uploadedFileName;
137 | private bool _disposed = false;
138 |
139 | // 写作风格选项
140 | private string[] styleOptions = new[]
141 | {
142 | "通俗易懂 - 面向初学者",
143 | "专业严谨 - 面向专家",
144 | "实战导向 - 强调动手实践",
145 | "深度分析 - 原理剖析"
146 | };
147 |
148 | // 目标读者选项
149 | private string[] audienceOptions = new[]
150 | {
151 | "初级开发者 - 0-2年经验",
152 | "中级开发者 - 2-5年经验",
153 | "高级开发者 - 5年以上经验",
154 | "架构师 - 技术决策者"
155 | };
156 |
157 | private string InputMode
158 | {
159 | get => inputMode;
160 | set
161 | {
162 | if (inputMode == value)
163 | {
164 | return;
165 | }
166 |
167 | inputMode = value;
168 | model.ReferenceContent = null;
169 | model.ReferenceUrls = null;
170 | uploadedFileName = null;
171 | }
172 | }
173 |
174 | private async Task HandleFileSelected(InputFileChangeEventArgs args)
175 | {
176 | var file = args.File;
177 | if (file == null)
178 | {
179 | return;
180 | }
181 |
182 | if (file.Size > 10485760)
183 | {
184 | if (!_disposed)
185 | {
186 | await InvokeAsync(() => Message.Warning("文件大小超过 10MB 限制"));
187 | }
188 | return;
189 | }
190 |
191 | uploadedFileName = file.Name;
192 |
193 | try
194 | {
195 | await using var stream = file.OpenReadStream(maxAllowedSize: 10485760);
196 | using var reader = new StreamReader(stream);
197 | model.ReferenceContent = await reader.ReadToEndAsync();
198 |
199 | if (!_disposed)
200 | {
201 | await InvokeAsync(() => Message.Success($"文件 {uploadedFileName} 读取成功"));
202 | }
203 | }
204 | catch (Exception ex)
205 | {
206 | if (!_disposed)
207 | {
208 | await InvokeAsync(() => Message.Error($"文件读取失败: {ex.Message}"));
209 | }
210 | uploadedFileName = null;
211 | }
212 | }
213 |
214 | private bool IsFormValid()
215 | {
216 | if (string.IsNullOrWhiteSpace(model.Topic))
217 | return false;
218 |
219 | return inputMode switch
220 | {
221 | "text" => !string.IsNullOrWhiteSpace(model.ReferenceContent),
222 | "file" => !string.IsNullOrWhiteSpace(model.ReferenceContent),
223 | "url" => !string.IsNullOrWhiteSpace(model.ReferenceUrls),
224 | _ => false
225 | };
226 | }
227 |
228 | private async Task OnSubmitAsync()
229 | {
230 | if (!IsFormValid())
231 | {
232 | if (!_disposed)
233 | {
234 | await InvokeAsync(() => Message.Warning("请完整填写必填项"));
235 | }
236 | return;
237 | }
238 |
239 | loading = true;
240 | await SafeStateHasChangedAsync();
241 |
242 | try
243 | {
244 | var taskId = await BlogService.CreateTaskAsync(model);
245 |
246 | if (_disposed) return;
247 |
248 | // 根据工作流模式跳转到不同页面
249 | var targetPage = model.WorkflowMode == "auto"
250 | ? $"/blog/auto-workflow/{taskId}"
251 | : $"/blog/workflow/{taskId}";
252 |
253 | var modeText = model.WorkflowMode == "auto" ? "全自动工作流" : "分步工作流";
254 | await InvokeAsync(() => Message.Success($"任务创建成功,正在跳转到{modeText}页面..."));
255 |
256 | // 延迟一下再跳转,让用户看到成功提示
257 | await Task.Delay(500);
258 |
259 | if (!_disposed)
260 | {
261 | Navigation.NavigateTo(targetPage);
262 | }
263 | }
264 | catch (Exception ex)
265 | {
266 | if (!_disposed)
267 | {
268 | await InvokeAsync(() => Message.Error($"创建任务失败: {ex.Message}"));
269 | }
270 | }
271 | finally
272 | {
273 | if (!_disposed)
274 | {
275 | loading = false;
276 | await SafeStateHasChangedAsync();
277 | }
278 | }
279 | }
280 |
281 | private async Task SafeStateHasChangedAsync()
282 | {
283 | if (!_disposed)
284 | {
285 | try
286 | {
287 | await InvokeAsync(StateHasChanged);
288 | }
289 | catch (ObjectDisposedException)
290 | {
291 | // 组件已被销毁,忽略此异常
292 | }
293 | }
294 | }
295 |
296 | public void Dispose()
297 | {
298 | _disposed = true;
299 | }
300 | }
301 |
302 |
--------------------------------------------------------------------------------