Correct Middleware

This commit is contained in:
Suphonchai Phoonsawat 2025-06-23 17:03:18 +07:00
parent f9d8fa285f
commit 0baa85e857
3 changed files with 157 additions and 47 deletions

View file

@ -39,14 +39,18 @@
<option name="autoReloadType" value="SELECTIVE" />
</component>
<component name="ChangeListManager">
<list default="true" id="85fddeb6-44fd-40a4-864f-89daec07db75" name="Changes" comment="" />
<list default="true" id="85fddeb6-44fd-40a4-864f-89daec07db75" name="Changes" comment="">
<change beforePath="$PROJECT_DIR$/.idea/.idea.BMA.EHR.Solution/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/.idea.BMA.EHR.Solution/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BMA.EHR.Application/Repositories/PermissionRepository.cs" beforeDir="false" afterPath="$PROJECT_DIR$/BMA.EHR.Application/Repositories/PermissionRepository.cs" afterDir="false" />
<change beforePath="$PROJECT_DIR$/BMA.EHR.Domain/Middlewares/ErrorHandlerMiddleware.cs" beforeDir="false" afterPath="$PROJECT_DIR$/BMA.EHR.Domain/Middlewares/ErrorHandlerMiddleware.cs" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="DpaMonitoringSettings">
<option name="autoShow" value="false" />
<option name="firstShow" value="false" />
</component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
@ -57,6 +61,7 @@
<setting file="file://$APPLICATION_CONFIG_DIR$/resharper-host/SourcesCache/bf9021a960b74107a7e141aa06bc9d8a0a53c929178c2fb95b1597be8af8dc/ExceptionDispatchInfo.cs" root0="FORCE_HIGHLIGHTING" />
<setting file="file://$PROJECT_DIR$/BMA.EHR.Application/Repositories/InsigniaPeriodsRepository.cs" root0="SKIP_HIGHLIGHTING" />
</component>
<component name="MetaFilesCheckinStateConfiguration" checkMetaFiles="true" />
<component name="ProjectColorInfo">{
&quot;customColor&quot;: &quot;&quot;,
&quot;associatedIndex&quot;: 2
@ -66,23 +71,23 @@
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">{
&quot;keyToString&quot;: {
&quot;.NET Launch Settings Profile.BMA.EHR.Leave: https.executor&quot;: &quot;Debug&quot;,
&quot;.NET Launch Settings Profile.BMA.EHR.Placement.Service: http.executor&quot;: &quot;Run&quot;,
&quot;RunOnceActivity.ShowReadmeOnStart&quot;: &quot;true&quot;,
&quot;RunOnceActivity.git.unshallow&quot;: &quot;true&quot;,
&quot;git-widget-placeholder&quot;: &quot;develop&quot;,
&quot;node.js.detected.package.eslint&quot;: &quot;true&quot;,
&quot;node.js.detected.package.tslint&quot;: &quot;true&quot;,
&quot;node.js.selected.package.eslint&quot;: &quot;(autodetect)&quot;,
&quot;node.js.selected.package.tslint&quot;: &quot;(autodetect)&quot;,
&quot;nodejs_package_manager_path&quot;: &quot;npm&quot;,
&quot;settings.editor.selected.configurable&quot;: &quot;preferences.lookFeel&quot;,
&quot;vue.rearranger.settings.migration&quot;: &quot;true&quot;
<component name="PropertiesComponent"><![CDATA[{
"keyToString": {
".NET Launch Settings Profile.BMA.EHR.Leave: https.executor": "Debug",
".NET Launch Settings Profile.BMA.EHR.Placement.Service: http.executor": "Debug",
"RunOnceActivity.ShowReadmeOnStart": "true",
"RunOnceActivity.git.unshallow": "true",
"git-widget-placeholder": "working",
"node.js.detected.package.eslint": "true",
"node.js.detected.package.tslint": "true",
"node.js.selected.package.eslint": "(autodetect)",
"node.js.selected.package.tslint": "(autodetect)",
"nodejs_package_manager_path": "npm",
"settings.editor.selected.configurable": "preferences.lookFeel",
"vue.rearranger.settings.migration": "true"
}
}</component>
<component name="RunManager" selected=".NET Launch Settings Profile.BMA.EHR.Placement.Service: http">
}]]></component>
<component name="RunManager" selected=".NET Launch Settings Profile.BMA.EHR.Leave: https">
<configuration name="BMA.EHR.CheckInConsumer" type="LaunchSettings" factoryName=".NET Launch Settings Profile">
<option name="LAUNCH_PROFILE_PROJECT_FILE_PATH" value="$PROJECT_DIR$/BMA.EHR.CheckInConsumer/BMA.EHR.CheckInConsumer.csproj" />
<option name="LAUNCH_PROFILE_TFM" value="net8.0" />
@ -566,6 +571,7 @@
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
<component name="UnityCheckinConfiguration" checkUnsavedScenes="true" />
<component name="UnityProjectConfiguration" hasMinimizedUI="false" />
<component name="VcsManagerConfiguration">
<option name="CLEAR_INITIAL_COMMIT_MESSAGE" value="true" />

View file

@ -58,7 +58,8 @@ namespace BMA.EHR.Application.Repositories
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", AccessToken.Replace("Bearer ", ""));
client.DefaultRequestHeaders.Add("api_key", _configuration["API_KEY"]);
var req = await client.GetAsync(apiPath);
var res = await req.Content.ReadAsStringAsync();

View file

@ -2,6 +2,7 @@
using BMA.EHR.Domain.Shared;
using Microsoft.AspNetCore.Http;
using System.Net;
using System.Text.Json;
namespace BMA.EHR.Domain.Middlewares
{
@ -23,6 +24,7 @@ namespace BMA.EHR.Domain.Middlewares
var response = context.Response;
var statusCode = response.StatusCode;
// ตรวจสอบว่า response ยังไม่ถูกส่งและเป็น status code ที่ต้องการจัดการ
if (!response.HasStarted &&
(statusCode == (int)HttpStatusCode.Unauthorized || statusCode == (int)HttpStatusCode.Forbidden))
{
@ -35,43 +37,144 @@ namespace BMA.EHR.Domain.Middlewares
};
response.ContentType = "application/json";
await response.WriteAsJsonAsync(responseModel);
// ใช้ JsonSerializer แทน WriteAsJsonAsync เพื่อความปลอดภัย
var jsonResponse = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(jsonResponse);
}
}
catch (Exception error)
{
var response = context.Response;
await HandleExceptionAsync(context, error);
}
}
if (!response.HasStarted)
private static async Task HandleExceptionAsync(HttpContext context, Exception error)
{
var response = context.Response;
// ตรวจสอบว่า response ยังไม่ถูกส่งไป
if (response.HasStarted)
{
// ถ้า response เริ่มแล้ว ไม่สามารถแก้ไขได้ แค่ log
Console.WriteLine("Cannot write error response, stream already started.");
Console.WriteLine($"Error: {error}");
return;
}
try
{
// Clear response เฉพาะเมื่อยังไม่ได้เริ่มส่ง
response.Clear();
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
// สร้าง error message
var msg = error.Message;
var inner = error.InnerException;
while (inner != null)
{
response.Clear();
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
var msg = error.Message;
var inner = error.InnerException;
while (inner != null)
{
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
}
var responseModel = new ResponseObject
{
Status = response.StatusCode,
Message = GlobalMessages.ExceptionOccured,
Result = msg
};
await response.WriteAsJsonAsync(responseModel);
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
}
else
var responseModel = new ResponseObject
{
// logging กรณีที่ response เริ่มถูกส่งแล้ว
Console.WriteLine("Cannot write error response, stream already started.");
Console.WriteLine(error);
}
Status = response.StatusCode,
Message = GlobalMessages.ExceptionOccured,
Result = msg
};
// ใช้ JsonSerializer และ WriteAsync เพื่อหลีกเลี่ยงปัญหา stream
var jsonResponse = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(jsonResponse);
}
catch (Exception writeError)
{
// ถ้าเขียน response ไม่ได้ ให้ log error
Console.WriteLine("Failed to write error response:");
Console.WriteLine($"Original Error: {error}");
Console.WriteLine($"Write Error: {writeError}");
}
}
}
}
// using BMA.EHR.Domain.Common;
// using BMA.EHR.Domain.Shared;
// using Microsoft.AspNetCore.Http;
// using System.Net;
//
// namespace BMA.EHR.Domain.Middlewares
// {
// public class ErrorHandlerMiddleware
// {
// private readonly RequestDelegate _next;
//
// public ErrorHandlerMiddleware(RequestDelegate next)
// {
// _next = next;
// }
//
// public async Task Invoke(HttpContext context)
// {
// try
// {
// await _next(context);
//
// var response = context.Response;
// var statusCode = response.StatusCode;
//
// if (!response.HasStarted &&
// (statusCode == (int)HttpStatusCode.Unauthorized || statusCode == (int)HttpStatusCode.Forbidden))
// {
// var responseModel = new ResponseObject
// {
// Status = statusCode,
// Message = statusCode == (int)HttpStatusCode.Unauthorized
// ? GlobalMessages.NotAuthorized
// : GlobalMessages.ForbiddenAccess
// };
//
// response.ContentType = "application/json";
// await response.WriteAsJsonAsync(responseModel);
// }
// }
// catch (Exception error)
// {
// var response = context.Response;
//
// if (!response.HasStarted)
// {
// response.Clear();
// response.ContentType = "application/json";
// response.StatusCode = (int)HttpStatusCode.InternalServerError;
//
// var msg = error.Message;
// var inner = error.InnerException;
// while (inner != null)
// {
// msg += $" {inner.Message}\r\n";
// inner = inner.InnerException;
// }
//
// var responseModel = new ResponseObject
// {
// Status = response.StatusCode,
// Message = GlobalMessages.ExceptionOccured,
// Result = msg
// };
//
// await response.WriteAsJsonAsync(responseModel);
// }
// else
// {
// // logging กรณีที่ response เริ่มถูกส่งแล้ว
// Console.WriteLine("Cannot write error response, stream already started.");
// Console.WriteLine(error);
// }
// }
// }
// }
// }