Does a call to MapRazorPages() constitute a call to UseEndpoints()? - asp.net

According to the documentation for UseRouting(), we must call UseEndpoints() afterward:
A call to UseRouting(IApplicationBuilder) must be followed by a call to UseEndpoints(IApplicationBuilder, Action) for the same IApplicationBuilder instance.
But in some code samples (e.g. here) I see UseRouting() calls with UseEndpoints() omitted and MapRazorPages() used instead. Is this safe?
I entered this query into ChatGPT:
What is the difference between App.MapRazorPages and App.UseEndpoints(Sub(Routes) Routes.MapRazorPages)?
...and it returned this helpful answer:
App.MapRazorPages is a method that configures the routing for Razor pages in an ASP.NET Core application. It adds a default route for all Razor pages, which is {page}/{handler?}, where page is the name of the Razor page and handler is the name of an optional handler method defined within the page.
App.UseEndpoints is a method that enables you to specify a pipeline of middleware that will be executed when a request is received by the application. Within the lambda expression provided to UseEndpoints, you can call MapRazorPages to add a route for Razor pages to the pipeline.
So, in short, App.MapRazorPages is a specific method that configures routing for razor pages, while App.UseEndpoints is a more general method that allows you to specify a pipeline of middleware and register various types of endpoints, including razor pages, in the application.
All well and good. Very nice. But what about the admonition from the documentation, that we must call UseEndpoints() at some point after we call UseRouting()? Is it safe to rely on only a call to MapRazorPages() to fulfill that requirement?
This answer seems to indicate so, but I'd like to make sure before I go stringing things together that I don't fully understand.
---EDIT---
Well, go figure.
I consulted the almighty ChatGPT on this one (should've done that at first, I guess) and he boomed down:
No, it is not safe to rely on a call to MapRazorPages() as a substitute for the required call to UseEndpoints().
UseRouting() is used to enable routing in an ASP.NET Core application. It sets up the routing system and prepares the app to handle incoming requests.
MapRazorPages() is an extension method that can be used to configure Razor pages in an ASP.NET Core application. It adds a Razor pages endpoint to the application's endpoint routing table, which allows the app to handle requests for Razor pages.
UseEndpoints() is used to define the endpoints for an ASP.NET Core application. It adds a route to the application's endpoint routing table for each endpoint defined within the lambda passed to it.
So, while MapRazorPages() can be used to configure razor pages and add a corresponding endpoint to the application's endpoint routing table, it cannot be used as a substitute for UseEndpoints(). UseEndpoints() is required to properly define the endpoints for an ASP.NET Core application and handle incoming requests.
So there we have it. But should we trust it? I'm a little bit wary, perhaps because I tend to prefer to live on the edge and not allow myself to be lulled into complacency by The Matrix.
Can someone corroborate?

It differs in different .NET versions.
For example, in .NET 5, you have to call app.UseEndpoints() to register routing. However, in .NET 6 you can register routes with a call to app.MapRazorPage() directly, leaving out both app.UseRouting() and app.UseEndpoints(). This is documented here.
Apps typically don't need to call UseRouting or UseEndpoints. WebApplicationBuilder configures a middleware pipeline that wraps middleware added in Program.cs with UseRouting and UseEndpoints. However, apps can change the order in which UseRouting and UseEndpoints run by calling these methods explicitly.

Related

Autofac lifetime scope issue with asp.net webforms

I'm having an issue with the lifetime scope of autofac lasting across a request in an asp.net webforms site.
I'm register a factory in auto fac thus:
builder.RegisterType<DoSomethingFactory>().As<IDoSomethingFactory>().InstancePerLifetimeScope();
This occurs in the app_start of course.
then I have a simple user control that calls a method of this factory
IDoSomethingFactory doSomethingFactory = Resolver.Resolve<IDoSomethingFactory>();
Number.Text = doSomethingFactory.DoSomething().ToString();
I have two instances of this control on a page, so that the DoSomething method should be called twice and the factory should be resolved twice also.
The first time I run the site, the contstructor for the DoSomethingFactory is fired, and there are 2 subsequent calls to the DoSomething method. The second request, results in 2 calls to the DoSomething method without a fresh new-ing up of the factory.
If I take out the InstancePerLifetimeScope on the registering then the factory is instantiated on each resolve. Most answers I have seen for this talk about an MVC site. I also have an MVC site and am using it in the same manner and it is working as requested, hence the need to question for asp.net webforms
To be clear I would like the factory to be instantiated once every request. Any help or ideas would be welcome.
Many thanks
Will
If you want to have one instance of your DoSomethingFactory per request you need to use the InstancePerHttpRequest extension method.
From the Autofac wiki: WebFormsIntegration
ASP.NET integration adds a special component lifetime that allows a component instance to live for the life of a single HTTP request. You can register components using the InstancePerHttpRequest() extension method in the Autofac.Integration.Web namespace.
So change your registration to:
builder.RegisterType<DoSomethingFactory>()
.As<IDoSomethingFactory>()
.InstancePerHttpRequest();

WebScriptServiceHostFactory vs WebServiceHostFactory

Can someone explain the difference between the two, when to use WebScriptServiceHostFactory vs WebServiceHostFactory? I understand when used they setup certain default behaviors on the endpoints so I don't have to. Otherwise the differences, is it just the WebScriptServiceHostFactory defaults to JSON messages, while WebServiceHostFactory defaults to XML (soap messages)? Using WebGet and WebInvoke, do both work on them, or does one not allow it? Also can I use UriTemplates, to build REST services, with either one?
The WebScriptServiceHostFactory is used almost exclusively to define services that will be consumed by the ASP.NET AJAX framework (it gives the JS client a "proxy" which can be used to call the service). If you're doing general-purpose WCF web (REST) programming, you should stick with the WebServiceHostFactory.
Some differences:
As you mentioned, the default response format is different (JSON in WScriptSHF, XML in WSHF)
UriTemplates are fully supported in WSHF, not in WScriptSHF
WebGet and WebInvoke work on both, but on WScriptSHF the only supported body style is WrappedRequest
Responses to calls to an endpoint created by WScriptSHF are wrapped in a JSON object; if the response to an operation (in JSON) was [1,2,3], the endpoint will return it as {"d":[1,2,3]}.
There may be others, but essentially, the guidance is to use the WScriptSHF only if you're using the ASP.NET AJAX framework (with the <asp:ScriptManager>) and the WSHF for everything else.

MVC 3/4 HttpModule or ActionFilter

I need to check some stuff (Cookies) for each request coming to my application.
In ASP.NET we've used HttpModule for this task , the question what should be used in MVC ? Some Global Filter , or I can Use HttpModuler as well, is there Any difference in Request PipeLine between MVC and regular ASP.NET ?
MVC is an abstraction over ASP.NET and therefore their "hooks" really depend at which level you want to inject your logic. An action filter will allow you to hook into MVC specific events:
OnActionExecuting – This method is called before a controller action is executed.
OnActionExecuted – This method is called after a controller action is executed.
OnResultExecuting – This method is called before a controller action result is executed.
OnResultExecuted – This method is called after a controller action result is executed.
Whereas an HttpModule only allows you to hook into ASP.NET (upon which MVC is built) specific events:
BeginRequest - Request has been started. If you need to do something at the beginning of a request (for example, display advertisement banners at the top of each page), synchronize this event.
AuthenticateRequest - If you want to plug in your own custom authentication scheme (for example, look up a user against a database to validate the password), build a module that synchronizes this event and authenticates the user in a way that you want to.
AuthorizeRequest - This event is used internally to implement authorization mechanisms (for example, to store your access control lists (ACLs) in a database rather than in the file system). Although you can override this event, there are not many good reasons to do so.
PreRequestHandlerExecute - This event occurs before the HTTP handler is executed.
PostRequestHandlerExecute - This event occurs after the HTTP handler is executed.
EndRequest - Request has been completed. You may want to build a debugging module that gathers information throughout the request and then writes the information to the page.
So it really depends on when you need to hook in your event and which events you need.
If the HttpModule worked well for you before then it will continue to with Mvc.
The other parts of your question are quite broad in scope and think you'd be as well reading a good article on asp.net-mvc pipeline and extensibility.
I've done similar things using a global action filter. It works quite well, and keeps your code integrated within your application.
An HTTP module works as well, of course, but this will mean seperating the code from your main application and maintaining it seperately. Unless your code spans multiple sites or is used in multiple applications, or needs to work with web forms sites, then I would use a global filter.

Which one to use Http Handler or Http Module

We want to do something like we have to execute some piece of code in each request to the application. We want to use this same code in multiple applications.
What this code will do is, this will check the incoming request and according to some conditions it will decide whether it has to redirect or not.
So while searching i found that we can use either http handler or http module. But i am not sure about which one has to chose in this case? Please give your suggestions.
HttpModule in this case. It sits in the pipeline where you can inspect each and every request.
How To Create an ASP.NET HTTP Module Using Visual C# .NET
http://support.microsoft.com/kb/307996
HttpHandler is altogether different thing. If you implement HttpHandler for existing file types such as .aspx etc, you will have implement what is already implemented by ASP.NET runtime which is beyond the scope of your requirement.

What happens if web services changes the parameters?

Say i'm having a web service that accepts two arguments and that is being called/consume in my application. Now after some time, the web service changes and accepts three arguments, hence in my application, would that be throwing an error, or i need to just update the web reference, or i need to recreate a web serivce or would that be working fine?
Let me know if any doubts
Thanks!
You could add optional parameters where if a parameter value isn't given to the method a default value is used.
From a "pure" architectural aspect, you should never change the signature of a method of a service once it's in use. You should version by creating a new method with a different namespace. But staying pure is sometimes difficult to do.
In your case you need to update the Web reference in the client application and then modify the code to pass in the appropriate parameter to the method in the service proxy.

Resources