ASP.Net Core 7 Error redirecting to Blazor page under Areas section - asp.net-core

_Host.cshtml.cs:
return RedirectToPage("/Account/Login/Index", new { area = "Identity" });
Error:
An unhandled exception occurred while processing the request.
AmbiguousMatchException: The request matched multiple endpoints. Matches:
/Account/Login/Index
/Account/Login
/_Host
Microsoft.AspNetCore.Routing.Matching.DefaultEndpointSelector.ReportAmbiguity(CandidateState[] candidateState)

It's because I use ASP.Net Core Identity scaffolded pages which has the Login in Areas/Identity/Pages/Account/<foo>.cshtml. I tried to move them into Areas/Identity/Pages/Account/Login/<foo>.cshtml and ASP.Net Core is confused by that! Duh!

Related

TraceId, RequestId, and TraceIdentifier in ASP.NET Core

I'm wondering how ASP.NET Core and Microsoft.Extensions.Logging assigns TraceId, RequestId, and TraceIdentifier. When looking through my log after making a request to my website I see the following information logged from Microsoft.Extensions.Logging:
TraceId: e57eb4708135dd43a914ee9e98165b1b
RequestId: 80000389-0006-ee00-b63f-84710c7967bb
I also log errors happening from ASP.NET Core through custom middleware. On the same request as above I see an error in the same log with the following information:
TraceIdentifier: 80000389-0006-ee00-b63f-84710c7967bb
The value 80000389-0006-ee00-b63f-84710c7967bb looks like the request GUID assigned by ASP.NET Core which makes sense when looking at the RequestId property from Microsoft.Extensions.Logging. But ASP.NET Core logs the request id as TraceIdentifier which feels a little weird.
I would personally prefer having the value from Microsoft.Extension.Logging's TraceId in the TraceIdentifier property when doing custom logging from ASP.NET Core middleware. Any input would be appreciated.
Update - Since writing this question I did create an issue on GitHub which were pretty much ignored and then closed because of inactivity :( https://github.com/dotnet/aspnetcore/issues/31747

Any alternatives to aspnet-request:serverVariable when using NLog with .Net Core?

As stated on the NLog GitHub the ${aspnet-request:serverVariable=String} layout renderer is not supported in .Net Core.
The documentation doesn't provide alternatives to many of the variables available under serverVariable.
My question is, are there any alternatives? Like to access remote address, server name, port etc? Or do I just have to write a bunch of custom layout renderers documented here and dependency inject all the stuff by hand?
For ASP.NET Core there as many new layout renders. The reason is that the API of ASP.NET Core is very different and the server variables can't be read like in ASP.NET (so non-core)
There are currently 13 layout renders for ASP.NET Core that renders a part of the request.
${aspnet-request} - ASP.NET Request variable.
${aspnet-request-contenttype} - ASP.NET Content-Type header (Ex. application/json)
${aspnet-request-cookie} - ASP.NET Request cookie content.
${aspnet-request-form} - ASP.NET Request form content.
${aspnet-request-headers} - ASP.NET Header key/value pairs.
${aspnet-request-host} - ASP.NET Request host
${aspnet-request-ip} - Client IP.
${aspnet-request-method} - ASP.NET Request method (GET, POST etc).
${aspnet-request-posted-body} - ASP.NET posted body / payload
${aspnet-request-querystring} - ASP.NET Request querystring.
${aspnet-request-referrer} - ASP.NET Request referrer.
${aspnet-request-url} - ASP.NET Request URL.
${aspnet-request-useragent} - ASP.NET Request useragent.
See also https://nlog-project.org/config/?tab=layout-renderers&search=package:nlog.web.aspnetcore
If you need something else, you could indeed create a custom renderer. If you need the http request you could use:
AspNetLayoutRendererBase.Register("aspnet-request-myrenderer", (logevent, httpcontext, config) => ... );
You need to reference the NLog.Web.AspNetCore package for that.

ASP.NET Core Openiddict throws "An OpenID Connect response cannot be returned from this endpoint"

I follow instruction in openiddict server example using password flow from https://github.com/openiddict/openiddict-samples/tree/master/samples/PasswordFlow
but have no success.
It throws InvalidOperationException: An OpenID Connect response cannot be returned from this endpoint at route /connect/token:
return SignIn(ticket.Principal, ticket.Properties, ticket.AuthenticationScheme);
Postman params:
Content-Type: application/x-www-form-urlencoded
Params: username=..&password=...&grantType=password&scope=offline_access+profile+email
I spent my day for researching but there is no information about cannot be returned from this endpoint exception. And many people can run openiddict example except me.
Here is apart of Startup.cs:
services.AddEntityFrameworkSqlite()
.AddDbContext<MisapayContext>(options =>
{
options.UseOpenIddict<int>();
});
//....
services.AddOpenIddict<int>()
.AddEntityFrameworkCoreStores<MisapayContext>()
.DisableHttpsRequirement()
.EnableTokenEndpoint("/connect/token")
.EnableLogoutEndpoint("/connect/logout")
.EnableUserinfoEndpoint("/connect/userinfo")
.UseJsonWebTokens()
.AllowPasswordFlow()
.AllowRefreshTokenFlow()
.AddEphemeralSigningKey();
services.AddMvc(config =>
{
config.Filters.Add(new ApiExceptionFilter());
}).AddJsonOptions(options =>
{
options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
options.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Local;
});
Edited: I think problem is OpenIdConnectRequest, it can not be binded if use:
OpenIddictBuiler.AddMvcBinders()
Will throws The OpenID Connect request cannot be retrieved from the ASP.NET context.`
Otherwise, remove it, OpenIdConnectRequest in AuthorizationController can get properly. And I can get request information such as username, password grantType etc... Strange... right?
Some other information:
Asp.net Core SDK 1.1
Project.json : https://gist.github.com/trinvh/47f29468887c209716098bc4c76181a7
Startup.cs: https://gist.github.com/trinvh/75b7a12fbee754d0ea8cf251f2da9fe9
AuthorizationController.cs: https://gist.github.com/trinvh/089015b2573cae550856631e72b81374
Any help will be appreciated!
Okay, here's what's happening:
You've configured OpenIddict to use /connect/token as the token endpoint address.
The token request you send via Postman points to /connect/token/, which is actually a totally different URL (/connect/token != /connect/token/).
Since the address differs from the registered endpoint path, OpenIddict doesn't handle the request and refuses to consider it as a token request.
For some reasons, MVC accepts to handle your /connect/token/ request and invokes the Exchange action, even though the route doesn't match the requested URL.
Since you haven't registered the OpenIddict MVC binder in the MVC options, MVC uses its default binder to construct the OpenIdConnectRequest object, which allows the OpenIdConnectRequest.GrantType parameter to be resolved from the invalid grantType parameter (it wouldn't happen with the dedicated OpenIddict binder).
Your token endpoint action ends up calling SignIn to return a token response.
Under the hood, OpenIddict detects that you called SignIn outside the normal token request processing - since it didn't consider the request as a token request, due to the paths difference - and aborts this unsafe operation by throwing an InvalidOperationException.
I'll ping the MVC folks to make sure they are aware of this bug.
Edit: after some research, it looks like this behavior is "by design" and was inherited from ASP.NET MVC. I opened a feature request in the aspnet/Mvc repository to add a new way to use "strict comparison" for routes matching.

Equivalent of HttpContext.IsCustomErrorEnabled is ASP.NET CORE

I have a lot of filters, which are using HttpContext.IsCustomErrorEnabled in MVC 5. One of such filter is JsonExceptionFilter, to simply return status without full error when exception is fired on Production environment. The details of exception are returned based on CustomeErrors enabled. So in rare cases I can see production/staging error just by chanign this option in web.config. However in ASP.NET Core there is no such option because redirection is done by ExceptionHandler middleware.
Is there any way to check if redirection (custom error) is enabled?

redirect to custom "access denied" page for ASP.NET Core

I writing an ASP.NET Core 1.0 website that uses Windows Authentication. I have implemented Authorization and that is working as expected. Currently, when Authentication fails for a given user, a generic "HTTP 403" error page is shown.
How can I configure ASP.NET Core so that it redirects to my own custom "access denied" page?
I tried the approach outlined in this article, but it didn't work for me (maybe because I'm using Windows Auth instead of Forms Auth?)
How to redirect unauthorized users with ASP.NET MVC 6
Any help would be appreciated.
Use the status code pages middleware.
app.UseStatusCodePages(async context => {
if (context.HttpContext.Response.StatusCode == 403)
{
// your redirect
}
});
You can also choose more generic approach via app.UseStatusCodePagesWithRedirects. The middleware can handle redirects (with either relative or absolute URL paths), passing the status code as part of the URL. For example the following will redirect to ~/errors/403 for 403 error:
app.UseStatusCodePagesWithRedirects("~/errors/{0}");