I have the following Owin Startup file:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
appBuilder
.Use(async (context, next) =>
{
appBuilder.Properties["User"] = "User1"; // MapWhen is called before this
await next.Invoke();
})
.MapWhen(
context => string.IsNullOrEmpty(appBuilder.Properties["User"] as string),
(builder) =>
{
builder.ThrowCustomException(); // This is called before setting the property
})
.MapWhen(
...
)
.MapWhen(
...
)
.Run(async context => {
await context.Response.WriteAsync(appBuilder.Properties["User"].ToString());
});
}
}
public static class Extensions
{
public static IAppBuilder ThrowCustomException(this IAppBuilder appBuilder)
{
throw new Exception();
}
}
I want to set the appBuilder.Properties["User"]
property to some value. I want that property to have a valid value always. However, when I run the application, the MapWhen() function, which throws exception if the User property does not have a value, is executed before the value for the User property is set. The Use() function is executed only after this MapWhen().
How to set the User property value before the MapWhen() function execution? Or, is there any better way to set the property value before MapWhen() execution?
You can use IAppBuilder.Use
and terminal middleware IAppBuilder.Run
(constructs final response, so always executed last) in a bunch.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app
.Use(async (context, next) =>
{
app.Properties["User"] = "User1";
await next();
})
.Run(async context => {
if (string.IsNullOrEmpty(app.Properties["User"] as string))
{
app.ThrowCustomException();
}
await context.Response.WriteAsync(app.Properties["User"].ToString());
});
}