I have a new Win 2008 Server VM. I've just installed UDDI website from the BizTalk 2010 DVD. When I try to browse to the page: http://localhost/uddi I get the following error, can anyone please help?
The website's app pool is running under a local admin account in integrated mode. If I change the app pool to classic mode then I get an exception that it can't reach the UDDI services database. This is installed on a local SQL Server 2008 instance of which the app pool ID is a db owner.
<html>
<head>
<title>Request is not available in this context</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '/uddi' Application.<hr width=100% size=1 color=silver></H1>
<h2> <i>Request is not available in this context</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br><br>
<b> Exception Details: </b>System.Web.HttpException: Request is not available in this context<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
Line 29: public void Application_Start( object source, EventArgs e )
Line 30: {
<font color=red>Line 31: Config.Refresh();
</font>Line 32: SessionCache.Init();
Line 33: }</pre></code>
</td>
</tr>
</table>
<br>
<b> Source File: </b> c:\Program Files (x86)\Microsoft UDDI Services\webroot\global.asax<b> Line: </b> 31
<br><br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpContext.get_Request() +11177464
UDDI.Localization.GetCulture() +168
UDDI.UDDIText.ConstructString(String stringToConstruct) +26
UDDI.UDDIText..ctor(String textName, Object[] textFormatParts) +59
UDDI.Config.Refresh() +1606
ASP.global_asax.Application_Start(Object source, EventArgs e) in c:\Program Files (x86)\Microsoft UDDI Services\webroot\global.asax:31
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4174081
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +205
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +336
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +350
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +382
[HttpException (0x80004005): Request is not available in this context]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11305670
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +88
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4342340
</pre></code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:2.0.50727.4961; ASP.NET Version:2.0.50727.4955
</font>
</body>
</html>
The IIS Integrated Mode-specific error may be a red herring. I'm running UDDI Services in IIS Integrated Mode with BizTalk 2010 on a Windows Server 2008 R2 x64 machine, but the database is housed on a local SQL instance, since installing UDDI on named instances (my available remote SQL Server) is all messed up.
Try to focus on the error about being able to reach the UDDI database, which is hard to troubleshoot here without further details (e.g., the exact error message). It may help to check out this thread for some suggestions about getting UDDI to work.
Related
In my jsp form, I get the value of month and year from the user, and return a webpage with relevant values. Here is my form:
<div class="modal-content animate" >
<div class="imgcontainer">
<span onclick="document.getElementById('month').style.display='none'" class="close" title="Close Modal">×</span>
<img src="doctor.jpg" alt="Avatar" class="avatar">
</div>
<form id="differentMonth" action="differentMonth" method="post">
<select name="month" multiple="multiple">
<%
int i;
for(i=1;i<=12;i++){
out.print("<option value=" + i +">" + Month.of(i) + "</option>");
}
%>
</select>
<select id="year" multiple="multiple">
<% int year1 = Integer.parseInt(Year.now().toString());
for(i=0;i<=10;i++){
out.print("<option value=" + i +">" + ( year1) + "</option>");
year1=year1-1;
}
%>
</select>
<input type="submit" name="submitted" value="submit" />
</form>
</centre>
</div>
</div>
</div>
This form takes the value from the user. In the dispatcher,
#RequestMapping(value = "/differentMonth", method = RequestMethod.POST)
public String differentMonth(#Validated DifferentMonth mon, Model model) {
System.out.println("In controller");
AccessDatabase ac = new AccessDatabase(AccessDatabase.id);
System.out.println(AccessDatabase.id);
ac.setStatusOfMonth(AccessDatabase.id,Integer.toString(mon.getMonth()),Integer.toString(mon.getYear()));
System.out.println(user.getUserName()+" "+mon.getMonth()+" "+mon.getYear());
model.addAttribute("database", ac);
return "user"; // Only this is important
}
The 'user' is also well defined, as this div is called from user.jsp itself. It worked the first time. Issue is when user is return by the servlet the second time
Here is the error:
HTTP Status 500 – Internal Server Error
Type Exception Report
M
essage Request processing failed; nested exception is java.lang.NullPointerException
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Root Cause
java.lang.NullPointerException
com.PricolAttendance.spring.controller.HomeController.differentMonth(HomeController.java:95)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.base/java.lang.reflect.Method.invoke(Method.java:567)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/7.0.99
Doesnt look like there is a logical error, as user.jsp works fine at first.
Please help.
In your code there are errors on mapping the form with the bean.
inside jsp add this on top:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
Write you open tag for form like this. ModelAttribute attribute map the element of the form with your bean.
<form id="form_id" action="url" method="post" modelAttribute="bean_name">
Add your form elements. the attribute path map the element inside form with the attribute of the bean.
<form:select id="sel_id" multiple="multiple" path="bean_attribute_mapped" />
Inside bean class put your annotations for validations.
Write the signature of your endpoint. #Valid enable validation and #ModelAttribute map the parameter with your bean.
#RequestMapping(value = "/differentMonth", method = RequestMethod.POST)
public String differentMonth(#Valid #ModelAttribute DifferentMonth mon, Model model) {
"Neither BindingResult nor plain target object for bean name 'loginCommand' available as request attribute"
I keep getting this Binding result error and nothing I've tried seems to be making it stop. I've seen other posts for this question, but none of them seem to fix whatever issue I'm having.
This is the first controller of my new project and I had some issues getting the xml squared away. I think that's all fixed, but if nothing looks off I supposed the problem could be there. The weird thing is that all this code is almost straight copied from another project I have and it works just fine.
Also I'm running on glassfish if that matters at all. Thanks in advance!
edit: The webpage is /morencore/login.jsp. I tried going to login.html assuming that would bring it up, but it only seems to work when I go to login.jsp. I believe I tried changing my controller to map to the jsp instead, but that did not work.
here is my login.jsp page:
<form:form method="post" modelAttribute="loginCommand">
<form:errors cssClass="error" element="p" />
<table border="0">
<tr>
<td align="right">Username:</td>
<td><form:input path="userName" /> <form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><form:password path="password" /> <form:errors path="password" cssClass="error" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" id="submit" name="submit" value="Log In" disabled="disabled"></td>
</tr>
</table>
</form:form>
and here is my controller:
#Controller
#ControllerAdvice
#RequestMapping("/login.html")
public class LoginController {
protected final Logger logger = LogManager.getLogger(getClass());
#Autowired
protected LoginValidator loginValidator;
#RequestMapping(method= RequestMethod.GET)
protected String initializeForm(#ModelAttribute("loginCommand")LoginCommand loginCommand,
BindingResult result,
ModelMap model)
{
logger.info("INITIALIZING LOGIN FORM");
model.addAttribute("loginCommand", new LoginCommand());
return "login";
}
#InitBinder("loginCommand")
protected void initBinder(ServletRequestDataBinder binder) throws Exception
{
binder.addValidators(loginValidator);
}
#RequestMapping(method=RequestMethod.POST)
protected String onSubmit(#ModelAttribute("loginCommand")LoginCommand loginCommand,
BindingResult result,
HttpServletRequest request) throws Exception
{
logger.info("validating login input");
loginValidator.validate(loginCommand, result);
if (result.hasErrors())
{
result.reject("login.failure");
return "login";
}
UserDao userDao = new UserDao();
User user = userDao.by_name(loginCommand.getUserName());
if (user == null
|| !user.getName().equals(loginCommand.getUserName())
|| !user.getPassword().equals(loginCommand.getPassword()))
{
result.reject("login.failure");
return "login";
}
return "redirect:main.html";
}
}
Here is my LoginCommand class:
#XmlRootElement
public class LoginCommand
{
private String userName;
private String password;
/** blah blah blah getters and setters*/
}
Here is the full stack trace as requested:
Neither BindingResult nor plain target object for bean name 'loginCommand' available as request attribute
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'loginCommand' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:142)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.autogenerateId(AbstractDataBoundFormElementTag.java:141)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.resolveId(AbstractDataBoundFormElementTag.java:132)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:116)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:422)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:142)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:84)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
at org.apache.jsp.login_jsp._jspx_meth_form_input_0(login_jsp.java:233)
at org.apache.jsp.login_jsp._jspService(login_jsp.java:126)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:791)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:338)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.glassfish.tyrus.servlet.TyrusServletFilter.doFilter(TyrusServletFilter.java:305)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:250)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:256)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
Among other things, it seems like your mappings need to be modified. Here is what I would try. There are a lot of adjustments so no guarantees on whether it will work completely, but it should get you in the right direction.
#Controller
public class LoginController {
protected final Logger logger = LogManager.getLogger(getClass()); //look at SLF4J instead. Then you're not tied to a specific logger and you use a facade.
#Autowired //may want to use constructor wiring instead on these
private LoginValidator loginValidator;
#Autowired
private UserDao userDao; //this should be wired and not simply instantiated - Spring won't know about it otherwise
#Autowired
private LoginValidator loginValidator;
#GetMapping("/login")
public String initializeForm(Model model) {
logger.info("INITIALIZING LOGIN FORM");
model.addAttribute("loginCommand", new LoginCommand());
return "login";
}
#PostMapping("/loginPost")
public String onSubmit(#ModelAttribute("loginCommand") LoginCommand loginCommand,
BindingResult result) throws Exception {
logger.info("validating login input");
loginValidator.validate(loginCommand, result);
if (result.hasErrors()) {
result.reject("login.failure");
return "login";
}
User user = userDao.by_name(loginCommand.getUserName());
if (user == null
|| !user.getName().equals(loginCommand.getUserName())
|| !user.getPassword().equals(loginCommand.getPassword())) { //you should really refactor this and move it outside of your controller. Just keep routing code in your controller, not logic
result.reject("login.failure");
return "login";
}
return "main"; //you should return just "main" or redirect:/main depending on what you're trying to do - you want the JSP to be processed. Leaving off the extension allows you to change frameworks without changing the server-side code and allows the page to be compiled. You could switch to Thymeleaf, for example, and not touch any of this code.
}
}
Add an action to your form:
<form:errors cssClass="error" element="p" />
<table border="0">
<tr>
<td align="right">Username:</td>
<td><form:input path="userName" /> <form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><form:password path="password" /> <form:errors path="password" cssClass="error" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" id="submit" name="submit" value="Log In"></td>
</tr>
</table>
For the next developer reading your code, I'd rename LoginCommand to something closer to what it actually is - like UserDetailsAdapter or something along those lines. I am assuming that LoginCommand will implement UserDetails from Spring Security if you're using that.
You may also want to consider updating your UserDao to have the method called findOneByUsername instead of by_name. The naming convention can help you later when you use Spring Repositories.
Lastly, look at Project Lombok for your beans. It'll save you lots of headaches.
I tried to authenticate user from MySQL database with BCrypt using this
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().usersByUsernameQuery(USER_LOGIN_QUERY).authoritiesByUsernameQuery(GET_USER_ROLE_QUERY)
.dataSource(dataSource).passwordEncoder(bCryptPasswordEncoder);
}
on those requests here
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll()
.antMatchers("/reg").permitAll().anyRequest().hasAuthority("ADMIN").anyRequest()
.authenticated().and().csrf().disable().formLogin().loginPage("/login").failureUrl("/login?error=true")
.defaultSuccessUrl("/").usernameParameter("username").passwordParameter("password").and()
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/").and()
.exceptionHandling().accessDeniedPage("/403");
}
on Login page
<div class="login-page">
<div class="form">
<form class="login-form" th:action="#{/login}" method="post">
<input type="text" placeholder="Username" id="username"
name="username" />
<input type="password" placeholder="Password" id="password"
name="password" />
<button type="submit">login</button>
<p class="message">
Not registered?
<a th:href="#{/reg}">Create an account</a>
</p>
</form>
<label th:if="${param.error}"
class="message text-danger text-capitalize">Login
credentials invalid</label>
</div>
</div>
Both overridden 'configure' methods do invoke when Web bootup. As I did put syserr to print out a random line to console from both.
I setup the datasource in application.properties and confirm it's correct since I can sign-up new user successfully. It's autowired
The USER_LOGIN_QUERY and GET_USER_ROLE_QUERY is normal too, it worked on MySQL query.
bCryptPasswordEncoder works since registering new user does encode password into hashed string. It's autowired
With jpa.show-sql = true, registering user(save to database) and other query do show SQL in the console. However, the two queries for authentication DON'T show up in the console log. So I assume login with post method never invoke authentication, hence, datasource, queries and passwordEncoder are not related
As a result, login always redirect me to failureUrl.
Where did I do wrong? How can I properly do authentication?
PS: On the other note,I follow the tutorial here https://github.com/gustavoponce7/SpringSecurityLoginTutorial , I build and run this tutorial source with no problem like above.
UPDATE: I tried new Spring Boot project, repeated the procedure to make a plain simple Spring Web with Security. jdbcAuthentication does authenticate for sometimes but giving me SQL query error. After correcting query error, BOOMM, nothing works again, even reverting edit won't do anything.
I am getting the following error whenever I try to do a simple form post in my MVC website.
Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Either BinaryRead, Form, Files, or InputStream was accessed before the internal storage was filled by the caller of HttpRequest.GetBufferedInputStream.
My sample form and actions are pretty basic...
#using (Html.BeginForm("Create", "Form"))
{
<div class="row action">
<div class="row">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
</div>
<input type="submit" id="save" class="btn" value="Save"/>
<input type="button" id="cancel" class="btn" value="Cancel"/>
</div>
}
And my Controller action is even more basic...
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
Please share your route.config file that might help solving this problem.
Just in case also try removing the perimeters from Html.BeginForm() remove the name of the action and controller. As MVC has strong naming systems because of which we don't need to add that info.
if above doesn't solve your issue Share your route file.
Short Version:
If I create a System.Web.HttpException as follows:
var exception = new HttpException(403, "Forbidden");
I would expect the following methods to return these values, but they don't:
var code = exception.GetHttpCode(); // is 0
var msg = exception.GetHtmlErrorMessage(); // is: null
Edit: In fact GetHttpCode() returns the correct number when being called the first time, but returns 0 when being called a second time:
var code = exception.GetHttpCode(); // is 403
code = exception.GetHttpCode(); // is 0
Long Version:
I am trying to unit-test the ASP.NET global exception handling method "Application_Error". This is an extract of the code:
var httpException = server.GetLastError() as HttpException;
if (httpException != null)
{
response.StatusCode = httpException.GetHttpCode();
response.StatusDescription = httpException.GetHtmlErrorMessage();
// ...
The unit test calls this method with a mock ServerUtilityBase object (Moq) which returns an HttpException when server.GetLastError() is called:
var exception = new HttpException(403, "Forbidden");
serverMock.Setup(server => server.GetLastError()).Returns(exception);
// ...
Unfortunately I had to find out that in the error handling code, httpException.GetHttpCode() and httpException.GetHtmlErrorMessage() methods return 0 or null, respectively.
What needs to be done to make a new HttpException(403, "Forbidden") return 403 or "Forbidden" when calling these methods?
Unfortunately it is not possible to create a Mock of the exception by subclassing it, because the said methods are sealed.
The httpException.GetHtmlErrorMessage() method is used to return the html which is sent to the browser by the ASP.NET Runtime, Patrick is correct in that you need to look at the .Message property to see the text "forbidden". If you want to see what the actual html looks like, you would need to supply an inner exception which is an exception type that the ErrorFormatter can use (for example a SecurityException).
var httpException = new HttpException(403, "Forbidden", new SecurityException());
Console.WriteLine(httpException.GetHttpCode());
Console.WriteLine(httpException.Message);
Console.WriteLine(httpException.GetHtmlErrorMessage());
will output:
403
Forbidden
<html>
<head>
<title>Security Exception</title>
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:bl
ack;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5p
x}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red
}
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maro
on }
pre {font-family:"Lucida Console";font-size: .9em}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy;
cursor:hand; }
</style>
</head>
<body bgcolor="white">
<span><H1>Server Error in '' Application.<hr width=100% size=1 color
=silver></H1>
<h2> <i>Security Exception</i> </h2></span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>The application attempted to perform an operati
on not allowed by the security policy. To grant this application the requi
red permission please contact your system administrator or change the applicatio
n's trust level in the configuration file.
<br><br>
<b> Exception Details: </b>System.Security.SecurityException: Securi
ty error.<br><br>
<b>Source Error:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
An unhandled exception was generated during the execution of the current web req
uest. Information regarding the origin and location of the exception can be iden
tified using the exception stack trace below.</code>
</td>
</tr>
</table>
<br>
<b>Stack Trace:</b> <br><br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code><pre>
[SecurityException: Security error.]
</pre></code>
</td>
</tr>
</table>
<br>
</body>
</html>