ASP.NET Web API Stack Trace Not Available - UseProblemDetails - c#

It has been a while since I developed an API so bear with me. I have created a new web API in the new .NET 5.0 framework. I have tried using Hellang.Middleware.ProblemDetails nuget for my error handling middleware. Seems to be working, but I cannot get any stack trace details to show for life the me, is there something I am missing?
I can only get the following details:
{"type":"https://httpstatuses.com/404","title":"Not
Found","status":404,"traceId":"00-02c4e89a990c5745bc4250cfad83d5e3-bb8c1dab98b44a44-00"}
Here is relevant code from my startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(AppSettings.DBConnectionString).UseLazyLoadingProxies());
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
services.AddProblemDetails(opts =>
{
// Control when an exception is included
opts.IncludeExceptionDetails = (ctx, ex) =>
{
// Fetch services from HttpContext.RequestServices
var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
return env.IsDevelopment();
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseProblemDetails();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

The returned ProblemDetails is for a 404. This wouldn't have a stack trace associated with it. By the looks of it in production if an exception occurs then you will get a raw 500, whereas in development it should render the stack in the developer exception page. Try introducing an obvious exception and see what is returned.
The following link (though outdated) provides some more details on this: https://andrewlock.net/handling-web-api-exceptions-with-problemdetails-middleware/

Usually the 404 is the error you get because the API can't find the method, try to be sure for the url.
For example
[HttpGet]
[Route("api/AnyNameyouWantForRoute/parameter")]
// your method in controller
Your url must be like
http://theIpYouChoose/api/AnyNameyouWantForRoute/parameter
If you have a typo in this you will not find the method to call and you will get 404

Related

Attaching middleware to a specific route in ASP.NET Core Web API?

Inside the configure, I can attach a global middleware using:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
....
app.UseMiddleware<MyMiddleware>();
...
}
This will apply to all actions.
However, I thought to myself, how can I attach a middleware to a specific route/action? (Sure I can put some if's inside the code but I don't like the approach)
But then I saw this:
app.UseEndpoints(endpoints =>
{
endpoints.Map("/version", endpoints.CreateApplicationBuilder()
.UseMiddleware<MyMiddleware>()
.UseMiddleware<VersionMiddleware>()
.Build())
.WithDisplayName("Version number");
}
This will work but will create a NEW endpoint /version.
Question
How can I attach custom middleware to an existing controller action route?
I've tried:
endpoints.Map("/weatherforecast", endpoints.CreateApplicationBuilder()
.UseMiddleware<MyMiddleware>()
.UseMiddleware<VersionMiddleware>()
.Build())
.WithDisplayName("Version number");
But it doesn't seem to affect. I see a regular response from the controller. Without new headers which the middleware adds.
You need the MapWhen
https://www.devtrends.co.uk/blog/conditional-middleware-based-on-request-in-asp.net-core
from the link, modified:
app.UseMiddlewareOne();
app.MapWhen(context => context.Request.Path.StartsWithSegments("/version", StringComparison.OrdinalIgnoreCase)), appBuilder =>
{
appBuilder.UseMiddlewareTwo();
});
app.UseMiddlewareThree();

How can I exclude some routes from UseStatusCodePagesWithReExecute?

I have a full-stack app in ASP.NET Core 5. The front-end is React and the back-end is OData.
I need to use app.UseStatusCodePagesWithReExecute("/"); in my Configure() method to redirect any unknown requests to index.html, as routing is handled by the client-side code.
The problem is that in OData standard, when a key in a GET request is invalid, it returns a 404 error. This error will cause a redirect to index.html as well.
My Question: How can I exclude any request that starts with /odata.svc from UseStatusCodePagesWithReExecute()?
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// generated swagger json and swagger ui middleware
// You can access the swagger ui at /swagger/index.html
app.UseSwagger();
app.UseSwaggerUI(x => x.SwaggerEndpoint("/swagger/v1/swagger.json", "ASP.NET Core Sign-up and Verification API"));
//app.UseCors("CorsPolicy");
// global cors policy
app.UseCors(x => x
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.All
});
app.UseRouting();
// global error handler
app.UseMiddleware<ErrorHandlerMiddleware>();
// custom jwt auth middleware
app.UseMiddleware<JwtMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.Select().Expand().Filter().OrderBy().Count().MaxTop(30);
// add an endpoint for an actual domain model
// registered this endpoint with name odata (first parameter)
// and also with the same prefix (second parameter)
// in this route, we are returning an EDM Data Model
endpoints.MapODataRoute("odata.svc", "odata.svc", GetEdmModel(app.ApplicationServices));
endpoints.EnableDependencyInjection();
endpoints.MapControllers();
// enable serving static files
endpoints.MapDefaultControllerRoute();
});
// Redirects any unknown requests to index.html
app.UseStatusCodePagesWithReExecute("/");
app.UseHttpsRedirection();
// Serve default documents (i.e. index.html)
app.UseDefaultFiles();
//Set HTTP response headers
const string cacheMaxAge = "1";
// Serve static files
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
// using Microsoft.AspNetCore.Http;
ctx.Context.Response.Headers.Append(
"Cache-Control", $"public, max-age={cacheMaxAge}");
}
});
}
This seems like an ideal use case for the UseWhen() extension method. This functionality is (under)documented by Microsoft, though #Paul Hiles has a more comprehensive write-up about it on his DevTrends blog. Basically, this allows you to conditionally inject middleware into your execution pipeline.
So, to conditionally exclude UseStatusCodePagesWithReExecute() if your request path starts with /odata.svc, you would simply wrap your UseStatusCodePagesWithReExecute() call with a UseWhen() condition, as follows:
app.UseWhen(
context => context.Request.Path.StartsWithSegments("/odata.svc"),
appBuilder =>
{
appBuilder.UseStatusCodePagesWithReExecute("/");
}
);

How to handle custom error in .NET Core app

I'm new to asp.net core and C#, sorry if my question sounds dumb, below is my code:
//startup.cs
...
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseExceptionHandler("/error.html");
app.Use(async (context, next) => {
await context.Response.WriteAsync("Hello");
await next();
});
app.Run(context => {
throw new Exception("Something has gone wrong");
});
}
we can see that the last middleware throws an exception, so I expects to see my custom error.html page to be displayed but I still see "Hello" on the page and there is no error.html content, how come?
The custom error page uses the above configuration.
context.Response.WriteAsync("Hello"); can block HttpHeaders, it sets HttpHeader._isReadOnly to true, and any subsequent operations on HttpHeader are invalid. So only Hello will be displayed.
If you delete the code, you will find that you still cannot reach the Error page.
That because when an exception occurs, it will take the route /errors.html to reach the corresponding custom error page.
If an exception occurs in the mvc, it can be reached normally; But when an exception occurs in the middleware, On the way to the custom error page, we pass the abnormal middleware again, so that the custom error page also produces an exception.
This is why the custom error page cannot be displayed.
If you want to throw a middleware exception, the easiest way is to use redirect instead of ExceptionHandler:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) => {
try
{
throw new Exception("Something has gone wrong");
}
catch (Exception)
{
//await context.Response.WriteAsync("Hello");
context.Response.Redirect("/error.html");
await next();
}
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
You need to add the error page middleware. Try:
app.UseDeveloperExceptionPage();
Also take a look at this for better explanation.

.NET Core 2.0 - Still seeing No 'Access-Control-Allow-Origin' header error

I'm at wit's end on this one. I've already researched other answers to similar questions on SO w/o any luck.
I'm fairly certain I've got CORS enabled correctly to allow incoming requests (in this case, POST requests) from all origins, but I'm seeing the error below:
Failed to load http://localhost:5000/expenses: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access. The response had HTTP status code 500.
Here's how I've enabled CORS in my webAPI project:
relevant methods in Startup.cs
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc();
services.AddDbContext<ExpensesDbContext>(options =>
options.UseMySQL(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IBaseDa<Accounts>, AccountsDataAccess>();
services.AddTransient<IExpensesDa, ExpensesDa>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
env.EnvironmentName = "Development";
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
.AllowCredentials());
app.UseMvc();
}
If i'm using .AllowAnyOrigin() and .AllowAnyMethod(), why am I seeing the error above?
Was scratching my head on this situation here for a while. I had CORS enabled properly, but some calls were still returning the Access-Control-Allow-Origin error. I found the problem... the sneaky sneaky problem...
Our problem was caused by how we were using app.UseExceptionHandler. Specifically, here's the code we were using, except our original code didn't have the context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); line.
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
var errorFeature = context.Features.Get<IExceptionHandlerFeature>();
var exception = errorFeature.Error;
var problemDetails = new ProblemDetails
{
Title = R.ErrorUnexpected,
Status = status,
Detail =
$"{exception.Message} {exception.InnerException?.Message}"
};
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.StatusCode = problemDetails.Status.GetValueOrDefault();
context.Response.WriteJson(problemDetails, "application/problem+json");
await Task.CompletedTask;
});
});
app.UseExceptionHandler is a much lower level function than controller actions, and thus does not take part in anything related to CORS natively. Adding context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); fixed the problem.
The combination of netCore2.0 (http://localhost:5000/) + Angular (http://localhost:4200) + chrome = Access-Control-Allow-Origin. I have had this issue before and it took me 3 days to realize that chrome will always throw this error. I think it is because chrome views localhost as the origin disregarding the port even tho the middleware explicitly tells it not too especially on POST requests.
I would try and define a policy in your startup.cs Configure services:
public void ConfigureServices(IServiceCollection services)
{
//add cors service
services.AddCors(options => options.AddPolicy("Cors",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
then in your Configure method I would add that:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//authentication added
app.UseAuthentication();
app.UseCors("Cors");
app.UseMvc();
}
... This most likely wont work and but try it any who.... This drove me mad and I needed the satisfaction of seeing if the request even attempted to hit the asp.netCore backend:
I used
If you really want to see I would clear your cache and cookies then add
IHttpContextAccessor to get low level control of whats going on in the request.
In my dilema with the same problem I needed angular to send an image. I was getting the annyoing
Origin error then through exprimenting I got the Image by injecting IHttpContextAccessor into my controller and
debugging
public void ConfigureServices(IServiceCollection services)
{
//add cors service
services.AddCors(options => options.AddPolicy("Cors",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc();
// register an IHttpContextAccessor so we can access the current
// HttpContext in services by injecting it
//---we use to this pull out the contents of the request
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
you want to inject this into whatever controller u are
using to retrieve the json object of the POST request. Im going to use the example as Home controller:
public class HomeController : Controller
{
// make a read only field
private readonly IHttpContextAccessor _httpContextAccessor;
//create ctor for controller and inject it
public UserService(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
// now in your post method use this to see what the if anything came in through the request:
public async Task<IActionResult> Picload(IFormFile file){//---always null
// in my problem I was loading and image from.
var file = _httpContextAccessor.HttpContext.Request.Form.Files[0];
}
Using this it gave me access to the image chrome was giving me an Origin error about.
My crystal ball tells me that somewhere in your C# code an error appear in time of execution and this way the "return" statement of the service is never executed. So debug your code and fix the error so the response is returned to the browser.

OData v4 on .Net Core 1.1 missing /$metadata

Using .net Core 1.1, with the Microsoft.AspNetCore.OData libraries, I am able to get an OData endpoint working with my simple controller to perform get, $expand, and other queries. However, I can't get it to return the $metadata to be returned. This question ($Metadata with WebAPi OData Attribute Routing Not Working) is for the same problem, however the .Net APIs have changed since this was posted.
Is there a setting, flag, or something else I need to enable?
This (http://localhost:52315/odata) seems to return the meta data,
{
"#odata.context":"http://localhost:52315/odata/$metadata","value":[
{
"name":"Users","kind":"EntitySet","url":"Users"
},{
"name":"HelloComplexWorld","kind":"FunctionImport","url":"HelloComplexWorld"
}
]
}
this (http://localhost:52315/odata/$metadata) gives me the error:
An unhandled exception occurred while processing the request.
NotSupportedException: No action match template '$metadata'
in 'MetadataController'
Microsoft.AspNetCore.OData.Routing.Conventions.DefaultODataRoutingConvention.SelectAction(RouteContext routeContext)
My Startup.cs looks like this:
public void Configure(IApplicationBuilder app) {
app.UseDeveloperExceptionPage();
app.UseOData("odata");
app.UseMvcWithDefaultRoute();
}
public void ConfigureServices(IServiceCollection services) {
services.AddMvc().AddWebApiConventions();
services.AddSingleton<ISampleService, ApplicationDbContext>();
services.AddOData<ISampleService>(builder =>
{
builder.Namespace = "Sample";
builder.EntityType<ApplicationUser>();
builder.EntityType<Product>();
builder.Function("HelloComplexWorld").Returns<Permissions>();
});
}
NOTE: I can work around it by adding this at the start of my ConfigureServices(...) method, though it seems wrong given $metadata support should be part of the core platform.
app.Use(async (context, next) => {
if (0 == string.Compare(context.Request.Path, #"/odata/$metadata", true)) {
context.Request.Path = "/odata";
}
await next.Invoke();
});
I revisited this today and had more success using the Microsoft.AspNetCore.OData.vNext 6.0.2-alpha-rtm package. Referencing this example, the metadata and default OData routing worked as expected. My minimal configuration is:
public void ConfigureServices(IServiceCollection services)
{
services.AddOData();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Document>("Documents");
app.UseMvc(builder =>
{
builder.MapODataRoute("odata", modelBuilder.GetEdmModel());
});
}
The /odata/$metadata route should return "an XML representation of the service’s data model" (EDMX) (according to the OData v4 Web API documentation). This is not the same as the service root /odata/, which returns the top level description of resources published by the OData service (as shown in your example).
I encountered the same issue using the pre-release Microsoft.AspNetCore.OData 1.0.0-rtm-00015, since an official release is not yet available (see open issue on OData Web API repo).
To illustrate the point, you could manually emit the metadata, as in the crude example below. (You can find the InMemoryMessage class in the OData/odata.net GitHub repo.)
However, I would suggest waiting for an official release of OData ASP.NET Core as, quoting from the above issue, the "branch is still in its early stages and we may take a different approach once we have our architecture finalized". So things may well change... and $metadata should definitely work "out of the box"!
app.Use((context, func) =>
{
if (context.Request.Path.StartsWithSegments(new PathString("/data/v1/$metadata"), StringComparison.OrdinalIgnoreCase))
{
var model = app.ApplicationServices.GetService<IEdmModel>();
MemoryStream stream = new MemoryStream();
InMemoryMessage message = new InMemoryMessage() {Stream = stream};
ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
ODataMessageWriter writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model);
writer.WriteMetadataDocument();
string output = Encoding.UTF8.GetString(stream.ToArray());
return context.Response.WriteAsync(output);
}
return func();
});

Categories

Resources