ASP.Net Core Web API - ResponseCache attribute is not adding "Cache-Control" header to the reponse - asp.net-core-mvc

I have multiple controllers in my ASP .NET Core application and I am using ReponseCache attribute like this on a few methods:
//controller
[Route("api/[controller]")]
[EnableCors("CorsPolicy")]
public class InsightsApiController : Controller
//method
[Route("CoursesTextContent")]
[HttpGet]
[DecryptFilter]
[ResponseCache(Duration = 60)]
public IActionResult GetCoursesContent(string locale, string tabKey, string widgetType)
The issue that I am having is that for one controller this is working fine and I can see the response in chrome dev tools with "Cache-Control:public max-age=60" but in a different controller when I add this attribute its adding "Cache-Control:no-cache". I compared both controllers and methods in them and they are configured same. I have also tried to add ASP.NET Core middleware recommended here but same results. I am calling both methods from Angular2 webpage. Is there something I can do from the client side (request)? or something in the ASP.NET Core app setup?

You are missing a trailing parenthesis
[ResponseCache(Duration = 60]
needs to be
[ResponseCache(Duration = 60)]

I had a session middleware enabled in the startup.cs file of my ASNETCore webapi project. I removed it and its working for all calls/controllers now. Not sure why it was causing problem only with one Controller.

Related

REST and spring-mvc

Since REST based controller methods only return objects ( not views ) to the client based on the request, how can I show view to my user ? Or maybe better question what is a good way to combine spring-mvc web app with REST, so my user always get the answer, not in just ( for example ) JSON format, but also with the view ?
So far as I understood, REST based controller would be perfectly fitting to the mobile app ( for example twitter ), where views are handled inside the app and the only thing server has to worry about is to pass the right object to the right request. But what about the web app ?
I might be wrong in several things ( correct me if I am ), since I am trying to understand REST and I am still learning.
To simplify things - you basically have two options:
1) Build Spring MVC application.
2) Build REST backend application.
In case of first option - within your application you will have both backend and frontend (MVC part).
In case of second option you build only backend application and expose it through REST API. In most cases, you will need to build another application - REST client for your application. This is more flexible application because it gives you opportunity to access your backend application from various clients - for example, you can have Android, IOS applications, you can have web application implemented using Angular etc...
Please note, that thins are not so simple, you can within one application have both REST backend and REST client etc... This is just very very simplified in order that you get some general picture. Hope this clarified a little things.
There is some additional clarification related to REST and views worth learning. From your question, I can see that you mean "view" in a sense of UI(user interface) and typical MVC usage. But "view" can mean different things in a different contexts.
So:
JSON can be considered as a view for data
JSON is a representation of the resource, just like HTML is
JSON doesn't have style (unless you are not using a browser
extension, which most the users are not using)
The browser is recognizing HTML as a markup language and applying a
style to it
Both are media types
Both JSON and HTML are data formats
Both can be transferred over the wire
This method returns a view
#RequestMapping("/home")
String home(Model model) {
return "home"; // resources\templates\home.html
}
This method Returns String
#RequestMapping(value = "/home")
#ResponseBody
public String home() {
return "Success";
}
If you annotate a method with #ResponseBody, Spring will use a json mapper to generate the response. Instead of annotating every method with #ResponseBody you can annotate your class with #RestController.
If you want to return a view, you need to annotate the class with #Controller instead of #RestController and configure a viewresolver. Bij default spring will use thymeleaf as a viewresolver if you have spring-web as a dependency on the classpath. The return type of the method is a String that references the template to be rendered. The templates are stored in src/main/resources/templates.
You can find a guide on the spring website: https://spring.io/guides/gs/serving-web-content/

ASP.NET boilerplate: IInputDTO is not triggering Automatic Validation of DTO

I have created a DTO which implements IInputDTO.
public class CreateUserModel : IInputDto
When I receive a service call on my web api layer it doesn't seem to validate the DTO as it just goes through the flow of the service method
public async Task<HttpResponseMessage> Create(CreateUserModel createUserRequest)
I'm running ASP.NET Boilerplate 0.8.3
The support for ASP.NET boilerplate has answered me that this is currently not possible. Only classes which implement the IApplicationService are currently able to do this.
Link to issue on ASP.NET Boilerplate's issue page

WebAPI - Can it be used to Logout a user?

This method when called in a WebAPI controller from the client via an AJAX call returns a 200 code but the user gets re-authenticated upon a page refresh. What am I doing wrong?
[HttpPost]
[Route("logout")]
public IHttpActionResult Logout() {
AuthenticationManager.SignOut();
}
This works in a standard MVC controller as an ActionResult and a full page view, but it does not work via AJAX.
It looks like you're using a custom AuthenticationManager class because the one built into the framework doesn't look like it has a SignOut method.
http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager(v=vs.110).aspx
If that is the case, then does your AuthenticationManager class use the Session to store user info? Because WebAPI controllers do not have the same type of access to session that MVC controllers do. Reference for session in WebAPI:
Accessing Session Using ASP.NET Web API

VS2013 (RTW): Authentication differences in SPA template vs MVC5 template?

I've been playing with the new ASP.NET identity offerings in the VS2013 RTW MVC template (for "indivual user accounts"), and it works great: I am able to integrate Facebook login while customizing the way the data is serialized.
All well and good, but I noticed that if I create a new SPA app (instead of MVC), the authentication story seems very different. As an example:
From the SPA template:
public AccountController()
: this(Startup.UserManagerFactory(), Startup.OAuthOptions.AccessTokenFormat)
{
}
public AccountController(UserManager<IdentityUser> userManager,
ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
{
UserManager = userManager;
AccessTokenFormat = accessTokenFormat;
}
From the MVC template:
public AccountController()
: this(new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())))
{
}
public AccountController(UserManager<ApplicationUser> userManager)
{
UserManager = userManager;
}
This is just the difference in constructors of the Account controller. There are many, many other differences as well. With the MVC version I was able to easily derive my own context class from ApplicationDBContext, and use that to store my own tables alongside the authentication tables. I couldn't figure out how to customize the data storage in the SPA template.
Also, the SPA template includes and uses this class:
public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
The MVC template doesn't define (or use) this class.
I don't understand why there needs to be any differences at all between an MVC template and an SPA template.
Could anyone give me some guidance as to why authentication is handled so differently in these two templates? Starting a project from scratch, is there a preferred path to follow between the two? (It seems like the code in the MVC template is best, especially in terms of customizing how the data is stored by defining a custom EF Context class.)
Thanks...
-Ben
Take MVC and SPA project templates as Controller vs ApiController implementation sample.
As well as CookieAuthentication and oAuthAuthentication.
MVC uses Controller at the first request as well as all subsequent requests (having request defined Action Methods).
SPA uses Controller at the first request to SPA and all other interactions are handled by ApiController.
MVC uses cookie authentication.
SPA uses oAuth authentication.
Now in real apps, we need to take mix of both. Stating this, you can use the IdentityModel.cs (ApplicationDBContext) and it's customized copy of MVC project in your SPA too.
In oAuth implementation, the token is issued in GrantResourceOwnerCredentials method of ApplicationOAuthProvider. The user verification uses the same database of Identity framework by default. Moreover, oAuth provide authentication check in ApiController. In the sample implementation, oAuth's ResourceOwner flow is provided where user's username and password are verified.
In my opinion, templates are starting point examples.
I did notice the same thing when I first looked at all the posts about changing the model for the user and I couldn't find the model in the SPA template. Of course, the difference as #jd4u pointed out is that one is based on Controller and the other on ApiController.
So, I decided to see what it would take to make the SPA solution use the same Identity Model extension as the MVC template. I created a post that goes through the process that I went through. There is a link at the bottom to download the code from GitHub.

From web forms to Razor

I've got an .net 2.0 web forms site that has just been upgraded to .net 4. Now I'd like to use the Razor syntax and some mvc helpers. Could anyone give a step by step procedure to start using it?
(Yes, I know mixing different view engines is not straight forward, but I'm not asking for that. Just to be able to create a new _layout, and a new ContentPage.cshtml and start using some of the mvc helpers and get that to work in parallell with the old pages - I'll duplicate the masterpage functionality, so that new pages will be written using razor, and old pages bugfixed in webform with the old masterpage)
I just need to know the following:
What assemblies do I need to include
What changes to web.config do I need
Any other changes?
Thanks for any help
Larsi
Scott hanselman has a great post about this:
Integrating ASP.NET MVC 3 into existing upgraded ASP.NET 4 Web Forms applications
You need to include System.Web.Mvc version 3.0.
In your web.config, you need to make sure that the UrlRoutingModule is registered as an HttpModule. Your IHttpHandler is created by the IRouteHandler implementation, which is an MvcRouteHandler in ASP.NET Mvc.
You also will need to register your routes in your Global.asax to setup routing. The default Route registration (for an MVC2 project) looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
I'm not sure if they have made any changes to that in Mvc 3 or not, but you can find out by creating a new Mvc Web Application project in Visual Studio and opening up the Global.asax
You may take a look at the upgrading an ASP.NET MVC 2 Project to ASP.NET MVC 3 guide. If you have a classic WebForms application (not MVC) then there is no migration => there is a rewrite.
This converter tool will get you a head start:
http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790
Telerik wrote a command-line converter from aspx/ascx to cshtml for asp.net mvc. You can find that at: https://github.com/telerik/razor-converter
There is also a nice plugin for Visual Studio that uses the Telerik code at: http://visualstudiogallery.msdn.microsoft.com/d2bfd1ca-9808-417c-b963-eb1ea4896790

Resources