Skip to content

Commit 01b29d7

Browse files
committed
fix: #620
1 parent 537e848 commit 01b29d7

File tree

5 files changed

+41
-38
lines changed

5 files changed

+41
-38
lines changed

src/JsonApiDotNetCore/Configuration/JsonApiOptions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,12 @@ public class JsonApiOptions : IJsonApiOptions
3232
/// <summary>
3333
/// Whether or not stack traces should be serialized in Error objects
3434
/// </summary>
35-
public static bool DisableErrorStackTraces { get; set; }
35+
public static bool DisableErrorStackTraces { get; set; } = true;
3636

3737
/// <summary>
3838
/// Whether or not source URLs should be serialized in Error objects
3939
/// </summary>
40-
public static bool DisableErrorSource { get; set; }
40+
public static bool DisableErrorSource { get; set; } = true;
4141

4242
/// <summary>
4343
/// Whether or not ResourceHooks are enabled.

src/JsonApiDotNetCore/Controllers/BaseJsonApiController.cs

+8-8
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,7 @@ public virtual async Task<IActionResult> PostAsync([FromBody] T entity)
141141
return Forbidden();
142142

143143
if (_jsonApiOptions.ValidateModelState && !ModelState.IsValid)
144-
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(GetAssociatedResource()));
144+
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>());
145145

146146
entity = await _create.CreateAsync(entity);
147147

@@ -155,7 +155,7 @@ public virtual async Task<IActionResult> PatchAsync(TId id, [FromBody] T entity)
155155
return UnprocessableEntity();
156156

157157
if (_jsonApiOptions.ValidateModelState && !ModelState.IsValid)
158-
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>(GetAssociatedResource()));
158+
return UnprocessableEntity(ModelState.ConvertToErrorCollection<T>());
159159

160160
var updatedEntity = await _update.UpdateAsync(id, entity);
161161

@@ -181,12 +181,12 @@ public virtual async Task<IActionResult> DeleteAsync(TId id)
181181
return NoContent();
182182
}
183183

184-
internal Type GetAssociatedResource()
185-
{
186-
return GetType().GetMethod(nameof(GetAssociatedResource), BindingFlags.Instance | BindingFlags.NonPublic)
187-
.DeclaringType
188-
.GetGenericArguments()[0];
189-
}
184+
//internal Type GetAssociatedResource()
185+
//{
186+
// return GetType().GetMethod(nameof(GetAssociatedResource), BindingFlags.Instance | BindingFlags.NonPublic)
187+
// .DeclaringType
188+
// .GetGenericArguments()[0];
189+
//}
190190
}
191191
public class BaseJsonApiController<T>
192192
: BaseJsonApiController<T, int>

src/JsonApiDotNetCore/Extensions/IApplicationBuilderExtensions.cs

+4-8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using Microsoft.AspNetCore.Builder;
77
using Microsoft.AspNetCore.Hosting;
88
using Microsoft.Extensions.DependencyInjection;
9+
using Microsoft.Extensions.Hosting;
910
using Microsoft.Extensions.Logging;
1011

1112
namespace JsonApiDotNetCore.Extensions
@@ -20,7 +21,6 @@ public static class IApplicationBuilderExtensions
2021
/// <returns></returns>
2122
public static void UseJsonApi(this IApplicationBuilder app)
2223
{
23-
DisableDetailedErrorsIfProduction(app);
2424
LogResourceGraphValidations(app);
2525
using (var scope = app.ApplicationServices.CreateScope())
2626
{
@@ -38,14 +38,10 @@ public static void UseJsonApi(this IApplicationBuilder app)
3838
app.UseEndpoints(endpoints => endpoints.MapControllers());
3939
}
4040

41-
private static void DisableDetailedErrorsIfProduction(IApplicationBuilder app)
41+
public static void EnableDetailedErrors(this IApplicationBuilder app)
4242
{
43-
var webHostEnvironment = (IWebHostEnvironment) app.ApplicationServices.GetService(typeof(IWebHostEnvironment));
44-
if (webHostEnvironment.EnvironmentName == "Production")
45-
{
46-
JsonApiOptions.DisableErrorStackTraces = true;
47-
JsonApiOptions.DisableErrorSource = true;
48-
}
43+
JsonApiOptions.DisableErrorStackTraces = false;
44+
JsonApiOptions.DisableErrorSource = false;
4945
}
5046

5147
private static void LogResourceGraphValidations(IApplicationBuilder app)

src/JsonApiDotNetCore/Extensions/ModelStateExtensions.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ namespace JsonApiDotNetCore.Extensions
99
{
1010
public static class ModelStateExtensions
1111
{
12-
public static ErrorCollection ConvertToErrorCollection<T>(this ModelStateDictionary modelState, Type resourceType)
12+
public static ErrorCollection ConvertToErrorCollection<T>(this ModelStateDictionary modelState) where T : class, IIdentifiable
1313
{
1414
ErrorCollection collection = new ErrorCollection();
1515
foreach (var entry in modelState)
@@ -19,7 +19,7 @@ public static ErrorCollection ConvertToErrorCollection<T>(this ModelStateDiction
1919
continue;
2020
}
2121

22-
var targetedProperty = resourceType.GetProperty(entry.Key);
22+
var targetedProperty = typeof(T).GetProperty(entry.Key);
2323
var attrName = targetedProperty.GetCustomAttribute<AttrAttribute>().PublicAttributeName;
2424

2525
foreach (var modelError in entry.Value.Errors)

src/JsonApiDotNetCore/Formatters/JsonApiWriter.cs

+25-18
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
using System.Threading.Tasks;
44
using JsonApiDotNetCore.Internal;
55
using JsonApiDotNetCore.Serialization.Server;
6+
using Microsoft.AspNetCore.Mvc;
67
using Microsoft.AspNetCore.Mvc.Formatters;
78
using Microsoft.Extensions.Logging;
89
using Newtonsoft.Json;
@@ -32,33 +33,39 @@ public async Task WriteAsync(OutputFormatterWriteContext context)
3233
throw new ArgumentNullException(nameof(context));
3334

3435
var response = context.HttpContext.Response;
35-
using (var writer = context.WriterFactory(response.Body, Encoding.UTF8))
36+
using var writer = context.WriterFactory(response.Body, Encoding.UTF8);
37+
string responseContent;
38+
39+
if (_serializer == null)
40+
{
41+
responseContent = JsonConvert.SerializeObject(context.Object);
42+
}
43+
else
3644
{
3745
response.ContentType = Constants.ContentType;
38-
string responseContent;
39-
if (_serializer == null)
46+
try
4047
{
41-
responseContent = JsonConvert.SerializeObject(context.Object);
42-
}
43-
else
44-
{
45-
try
48+
if (context.Object is ProblemDetails pd)
4649
{
47-
responseContent = _serializer.Serialize(context.Object);
48-
}
49-
catch (Exception e)
50-
{
51-
_logger?.LogError(new EventId(), e, "An error ocurred while formatting the response");
5250
var errors = new ErrorCollection();
53-
errors.Add(new Error(400, e.Message, ErrorMeta.FromException(e)));
51+
errors.Add(new Error(pd.Status.Value, pd.Title, pd.Detail));
5452
responseContent = _serializer.Serialize(errors);
55-
response.StatusCode = 400;
53+
} else
54+
{
55+
responseContent = _serializer.Serialize(context.Object);
5656
}
5757
}
58-
59-
await writer.WriteAsync(responseContent);
60-
await writer.FlushAsync();
58+
catch (Exception e)
59+
{
60+
_logger?.LogError(new EventId(), e, "An error ocurred while formatting the response");
61+
var errors = new ErrorCollection();
62+
errors.Add(new Error(500, e.Message, ErrorMeta.FromException(e)));
63+
responseContent = _serializer.Serialize(errors);
64+
response.StatusCode = 500;
65+
}
6166
}
67+
await writer.WriteAsync(responseContent);
68+
await writer.FlushAsync();
6269
}
6370
}
6471
}

0 commit comments

Comments
 (0)