How to link CSS in asp core MVC - css

I can't get my CSS files to work. I keep getting error 404. Apologies if this is really straightforward but I just can't get it to work.
I have a project in visual studio with the following folder structure:
-Properties
-launchSettings.json
-wwwroot
-css
-site.css
-images
-script
-site.js
-Pages
-Shared
_layout.cshtml
-index.cshtml
-index.cshtml.cs
-appsettings.json
-Program.cs
-Startup.cs
my startup.cs file
namespace WebApp
{
public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
}
my _layout.cshtml page:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Welcome to JellyZone</title>
<link href="~/css/site.css" rel="stylesheet" type="text/css" />
<script src="~/script/site.js" type="text/javascript"></script>
</head>
<body onload="fadeIn()">
#RenderBody()
</body>
</html>
my index.cshtml is:
#page
#{ Layout = "~/Pages/Shared/_Login.cshtml";}
And whenever I try to debug this it gives me error 404.
I've looked online lots and tried using "#Use.Content("~/css/site.cs")" on the link and href and moving the folders into different locations etc.
Please help
Many thanks

Related

Spring Dispatcher Servlet causing issues when trying to load my CSS sytlesheets

When I load my JSP page home.jsp I include the stylesheet signIn.css. But something is happening where I get Failed to load resource: the server responded with a status of 404 (Not Found) for my stylesheet. I think my spring dispatcher servlet is looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css (w/o using spring I have no issues). I think its something with getServletMappings where it is cutting off the file location.
My CSS page is in the exact same location as my home.jsp page. I also set up my SpringMvcInitializer class and MvcConfiguration class as I'm using Spring boot. I also have a home controller. I am not using spring-dispatcher-servlet.xml.
//MvcConfiguration.java
package Configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import ShoppingCart.Cart;
#Configuration
#ComponentScan(basePackages="Controllers/")
#EnableWebMvc
public class MvcConfiguration extends WebMvcConfigurerAdapter {
#Bean
public ViewResolver getViewResolver()
{
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/");
resolver.setSuffix(".jsp");
return resolver;
}
#Bean
public Cart getCart(){
return new Cart();
}
}
//SpringMvcInitializer.java
package Configuration;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {MvcConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
//home.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%#include file="header.jsp" %>
<link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
</body
</html>
My jsp and css page are stored in
/customerPortal/src/main/webapp/WEB-INF/home.jsp
/customerPortal/src/main/webapp/WEB-INF/signIn.css
But on my eclipse console I get the following:
- DispatcherServlet with name 'dispatcher' processing GET request for [/customerPortal/signIn.css]
- Did not find handler method for [/signIn.css]
- No mapping found for HTTP request with URI [/customerPortal/signIn.css] in DispatcherServlet with name 'dispatcher'
And on my chrome console browser I get:
GET http://localhost:8035/customerPortal/signIn.css net::ERR_ABORTED 404 (Not Found)
Why is it looking for URI /customerPortal/signIn.css when my CSS file is stored at /customerPortal/src/main/webapp/WEB-INF/signIn.css ?
For your information, you can not directly access WEB-INF with URL, Java servlets will not allow it. moreover, do not place resources under WEB-INF
What should you do now?
Create a folder called, resources under webapp and then create a folder for css (resources/css). then place all css under css folder. and create another folder js and place all JavaScript files there.
then add this method to your MvcConfiguration class.
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
now you have your css inside the resources, then access it via
<link rel="stylesheet" href="resources/css/signIn.css" />
Solution for your current problem, but not recommend to put static resources under WEB-INF.
change your <link rel="stylesheet" href="/src/main/webapp/WEB-INF/signIn.css"> code to this
<style><%#include file="/WEB-INF/signIn.css"%></style>
best of luck...! Happy coding..!

Webapi returns html page instead of json

I have implemented an action filter attribute for token verification and if token is invalid then api response should return from this action filter.
public class TokenValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
bool isValidToken = FunctionToVerifyToken();
if (!isValidToken ))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("Unauthorized user")
};
return;
}
}
}
Response:
It goes to _layout.cshtml and returns whole html page instead of just returning "Unauthorized user"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sign in</title>
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<link href="/Content/styles.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.8.3.js"></script>
...
Update:
controller where I'm using this token:
public class ServiceController : ApiController
{
[AcceptVerbs("GET", "POST")]
[HttpGet]
[HttpPost]
[TokenValidation]
public object ChangePassword()
{
//my logic is token is valid. It returns json data and works fine.
}
}
The view returned is login page.
My WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{action}/{id}",
defaults: new { controller = "Service", id = RouteParameter.Optional },
constraints: null
);
}
}
In Global.ascx.cs add following line
GlobalConfiguration.Configure(FilterConfig.Register);
In FilterConfig.cs register method
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new TokenValidationAttribute());
}
I think your code are missing this below lines in your TokenValidationAttribute.cs action filter.
base.OnActionExecuting(actionContext); return; What this will do is it would get your formated result and display your result rather than displaying the view.
I returned response as:
actionContext.Response = actionContext.Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Unauthorized user");
and it returned "Unauthorized user" instead of whole html page.

Introductory Spring Boot MVC App - login failed because Could not verify the provided CSRF token because your session was not found

I am trying to write a simple introductory application via Spring Boot, Spring MVC, and Spring Security, but after submitting my Login-form I'm getting redirected a Whitelabel Error Page as a result of a 403 response. The error message is Could not verify the provided CSRF token because your session was not found.
Could anyone please tell me what I'm doing wrong? Should I be disabling CSRF filtering for the login endpoint somehow? And even though it seems to be saying a CSRF token was provided, I don't see one in the request's headers or in the form data... could that be the problem - that I'm not even providing a CSRF token?
/build.gradle
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.7.RELEASE'
}
}
apply plugin: 'groovy'
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile ('org.springframework.boot:spring-boot-starter-web') {
exclude module: 'spring-boot-starter-tomcat'
}
compile 'org.springframework.boot:spring-boot-starter-jetty'
compile 'org.springframework.boot:spring-boot-starter-actuator'
compile 'org.springframework.boot:spring-boot-starter-security'
compile 'org.codehaus.groovy:groovy-all:2.3.11'
compile 'javax.servlet:jstl:1.2'
testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile 'org.springframework.boot:spring-boot-starter-test'
testCompile 'org.springframework.security:spring-security-test'
}
/src/main/groovy/my.little.app.Application.groovy
#SpringBootApplication
#EnableWebMvc
#EnableAutoConfiguration
#ComponentScan
class Application extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return [WebMvcConfig.class, WebSecurityConfig.class]
}
protected Class<?>[] getServletConfigClasses() {
return [WebMvcConfig.class, WebSecurityConfig.class]
}
protected String[] getServletMappings() {
return [ "/" ]
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args)
}
}
/src/main/groovy/my.little.app.MainController.groovy
#Controller
class MainController {
#RequestMapping(path = '/', method = RequestMethod.GET)
public String index() {
return 'index'
}
}
/src/main/groovy/my.little.app.config.WebMvcConfig.groovy
#Configuration
#ComponentScan('my.little.app')
#EnableWebMvc
class WebMvcConfig extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry)
registry.addViewController('/index').setViewName('index')
registry.addViewController('/login').setViewName('login')
registry.addViewController('/secure_page').setViewName('secure_page')
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public ViewResolver internalResourceViewResolver() {
InternalResourceViewResolver bean = new InternalResourceViewResolver()
// bean.setViewClass(JstlView.class)
bean.setPrefix('/WEB-INF/views/')
bean.setSuffix('.jsp')
return bean
}
}
/src/main/groovy/my.little.app.config.WebSecurityConfig.groovy
#Configuration
#EnableWebMvc
#EnableWebSecurity
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity security) {
security
.authorizeRequests()
.antMatchers('/', '/index').permitAll()
.antMatchers('/login').anonymous()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage('/login').permitAll()
.defaultSuccessUrl('/secure_page')
.failureUrl('/login?error=true')
.and()
.logout()
.permitAll()
.logoutSuccessUrl('/login')
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder authBuilder) {
authBuilder
.inMemoryAuthentication()
.withUser('doug').password('las').roles('WIZARD')
}
}
/src/main/webapp/WEB-INF/views/index.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<div>Welcome to the Web Security Tutorial</div>
<form method="get" action="/login">
<input type="submit" value="Sign In" />
</form>
</body>
</html>
/src/main/webapp/WEB-INF/views/login.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<form method="post" action="login">
<div><label> User name: <input name="username" type="text"/></label></div>
<div><label> Password: <input name="password" type="password"/></label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
/src/main/webapp/WEB-INF/views/secure_page.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Web Security Tutorial</title>
</head>
<body>
<div>Don't worry, no one can see this but you. Here are your deepest darkest secrets...</div>
<form action="/logout">
<input type="submit" value="Log Out"/>
</form>
</body>
</html>

Viewbag variable in shared view _layout

I would like to use ViewBag values in the shared view of layout but provided from another controller. In particular, I would like to render the principal action and then add few variables, coming from another controller, that are used in a lot of pages (but not in all pages to justify the use of global variables).
Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css_custom")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#Html.Action("myAction", "myController")
<p>Value: #ViewBag.testval </p>
#RenderBody()
</body>
</html>
Controllers/myController.cs
namespace myProject.Controllers
{
public class myController : Controller
{
public void myAction() {
string test_value = "Hey!";
ViewBag.testval = test_value;
}
}
}
In the layout the only Viewbag variables that I can access are the ones of the action target of RenderBody.
You should return that view.
public ActionResult Index()
{
ViewBag.testval = "Test value";
return View();
}

Spring / Resource handler location

I have common problem in spring with resource locator and can not figure out where is problem (CSS style is not working:
My .JSP page and HTML code :
<head>
<link href="/css/basicStyle.css" rel="stylesheet" type="text/css"/>
</head>
My resource locator configuration :
#Configuration
#ComponentScan("loginsystem.controllers")
#EnableWebMvc
public class ServletConfig extends WebMvcConfigurerAdapter{
#Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
resolver.setViewClass(
org.springframework.web.servlet.view.JstlView.class);
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry)
{
registry.addResourceHandler("/css/**").addResourceLocations("/LoginSystem/WebContent/WEB-INF/css/");
}
}
SOLUTION :
After looking in other questions I have found solution :
<link href="${pageContext.request.contextPath}/css/basicStyle.css/" rel="stylesheet" type="text/css"/>
Can any one explain why pageContext is needed ?
Change the resources locations from "/LoginSystem/WebContent/WEB-INF/css/" to "/WEB-INF/css/"
There's a dedicated JSP tag for this:
<!doctype html>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<link href="<spring:url value="/css/basicStyle.css"/>"
rel="stylesheet" type="text/css"/>
If you want to have better resource handling support in your application, you may also want to register a ResourceUrlEncodingFilter in your application.

Resources