I am trying to run Server.Execute outside of the controller from an external function. I have tried passing numerous types of objects trying to get this to work, but each time I get an error saying Error: Error executing child request for [url]
This is how my code looks inside of the controller:
public async Task<ActionResult> Exec(){
var http = HttpContext; //<- doesn't work
http = HttpContext.ApplicationInstance.Context; //<- doesn't work
return execMethodAsync(http);
}
Then in another class the code is:
public async Task execMethodAsync(HttpContext context){
context.Server.Execute("/myurl"); // <-- Throws error
}
I have tried passing a number of object types to this method but still get this error.
I tried passing HttpContext, HttpContext.CurrentHandler, ControllerContext.HttpContext and even some other ones, but still get this error. It seems nearly impossible to run Server.Execute() outside of the controller. Can someone please help with executing Server.Execute outside of the controller?
A few things could be causing this, have you tried
HttpContext.Current.RewritePath("yourpage.aspx");
Related
So I am building a complex case here with inheritance and IOC, need to use ActivatorUtilities to inject instances and pass parameters... no matter what I do I get the following error:
System.InvalidOperationException: 'A suitable constructor for type
'blabla.ISimpleTest' could not
be located. Ensure the type is concrete and all parameters of a public
constructor are either registered as services or passed as arguments.
Also ensure no extraneous arguments are provided.'
So in order to discard what could be the problem and ensure there is no constructor issues, I created a very very simple scenario that gives me the same error.
startup.cs
services.AddScoped<ISimpleTest, SimpleTest>();
the class and the interface, very simple here:
public interface ISimpleTest
{
}
public class SimpleTest : ISimpleTest
{
public SimpleTest()
{
}
}
test
var theInstance = ActivatorUtilities.CreateInstance<ISimpleTest>(ServiceProvider);
Additional notes
The ServiceProvider instance is fine (the rest/entire application depends on it).
Tried with and without adding the public constructor(empty params)
Tried also constructor with params, same error.
Tried to specify the params[] parameter, by sending null or empty array, same issue.
Extra test:
Just to confirm it's properly registered, I tried to get the instance using the Service provider, and works without issues:
//No issues this way:
var yyy = ServiceProvider.GetService<ISimpleTest>();
What am I doing here wrong? According to documentations, this should be enough to work
Hello I use Thymealf and want to do a validirung against my database before I subbmitte.
When I call the controller I get the error:
Error resolving template [], template might not exist or might not be accessible by any of the configured Template Resolvers
I think the error comes from the fact that I don't returne a modal.
Is there a way to make a request without thymleaf ?
Controller
#GetMapping("/getByKey/{key}")
public KeyValuePair keyExists(#PathVariable("key") String key){
return ssdbService.getByKey(key);
}
or do I understand here something completely wrong ?
Use a #RestController instead of a #Controller if you want to return data.
You can also just annotate your method with #ResponseBody if you just want one method to return data instead of the entire controller.
#ResponseBody
#GetMapping("/getByKey/{key}")
public KeyValuePair keyExists(#PathVariable("key") String key){
return ssdbService.getByKey(key);
}
Below is a minimal example of the problem I am currently encountering:
using System.Net.WebSockets;
using AutoFixture;
using AutoFixture.AutoMoq;
using FluentAssertions;
using Xunit;
...
[Fact]
public void Test1()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = fixture.Create<WebSocket>();
sut.Should().NotBeNull();
}
[Fact]
public void Test2()
{
var fixture = new Fixture().Customize(new AutoMoqCustomization() { ConfigureMembers = true });
var sut = new Mock<WebSocket>().Object;
fixture.Inject(sut);
sut.Should().NotBeNull();
}
...
When I run the first test, I get the following exception:
AutoFixture.ObjectCreationExceptionWithPath : AutoFixture was unable to create an instance from Moq.Mock`1[System.IO.Stream] because creation unexpectedly failed with exception. Please refer to the inner exception to investigate the root cause of the failure.
Inner exception messages:
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
The second test succeeds.
I would like to be able to create an instance of a class using AutoFixture which takes a WebSocket as a constructor parameter, without the need to inject a mock object first (ultimately, so that I can use an AutoMoqData attribute, and get rid of some boilerplate). Have I got any misusage or misunderstanding going on here, or would this be better placed as a GitHub issue? In the interim, is there anything I can do to work around this issue?
You observe this issue because of the AutoFixture's factory discovery strategy. When you try to create an object of an abstract type, AutoFixture still inspects the type to find a static factory method to activate the object. In your particular case, the WebSocket type contains such methods, so some of them is used. It looks like it doesn't work well with auto-generated input values, so fails with an exception.
You can customize AutoFixture, to always mock the WebSocket type:
fixture.Register((Mock<WebSocket> m) => m.Object);
Just tested with the latest versions of products (AutoFixture 4.5.0, Moq 4.10.0) and it works like a charm.
I am writing a simple API that posts a json document to a single collection in DocumentDB. What is strange, is that I get no exception or indication of error when I try to add a document with the same id more than once.
public static async Task<ResourceResponse<Document>> CreateDocument(Database database, DocumentCollection collection, object obj)
{
try
{
Uri collUri = UriFactory.CreateDocumentCollectionUri(database.Id, collection.Id);
return await client.CreateDocumentAsync(collUri, obj, null, true);
}
catch (DocumentClientException e)
{
// nothing is ever caught...
}
}
The behavior I see is that the first document saves. I can see it in the document explorer. Then if I change data and keep the same id, the code appears to work, but the updated document does not actually get saved, however I dont get an exception as expected. Am I wrong to think there should be an exception here?
In the event of a conflict, DocumentDB throws a Microsoft.Azure.Documents.DocumentClientException with the message: {"Errors":["Resource with specified id or name already exists"]}.
The reason (most likely) you are not seeing the exception is that the code you have runs asynchronously. In other words, your code may be ending execution before the result of the create operation has returned. You can resolve the async method simply by calling .Result.
I have a Spring MVC controller with an action that's called using AJAX.
#SessionAttributes({"userContext"})
public class Controller
{
...
#RequestMapping(value = "/my-url", method= { RequestMethods.POST })
public ModelAndView doSomething(#ModelAttribute("userContext") UserContext context,
SessionStatus sessionStatus)
{
BusinessObject obj = doSomeBusinessLogic(context.getUserName());
sessionStatus.setComplete();
ModelAndView mav = new ModelAndView("jsonView");
mav.addObject("someInt", obj.getId());
return mav;
}
}
When I run this action, I get the following exception:
net.sf.json.JSONException: There is a cycle in the hierarchy!
at t.sf.json.util.CycleDetectionStrategy$StrictCycleDetectionStrategy.handleRepeatedReferenceAsObject(CycleDetectionStrategy.java:97)
at net.sf.json.JSONObject._fromBean(JSONObject.java:833)
at net.sf.json.JSONObject.fromObject(JSONObject.java:168)
at org.springframework.web.servlet.view.json.writer.jsonlib.PropertyEditorRegistryValueProcessor.processObjectValue(PropertyEditorRegistryValueProcessor.java:127)
at net.sf.json.JSONObject._fromMap(JSONObject.java:1334)
Truncated. see log file for complete stacktrace
After doing some debugging I found out that Spring is placing the UserContext object onto the ModelAndView that I am returning. If I hard-code my user name and remove the context object from the method's parameters, the action runs successfully. Is there a way to configure Spring to omit the ModelAttribute-annotated parameters from the returned ModelAndView? As you can see, sessionStatus.setComplete() has no effect.
I've had similar problems in the past with #SessionAttributes. By declaring #SessionAttributes({"userContext"}) you're telling Spring that you want "userContext" to always be available in the model, and so Spring has no choice but to send your UserContext object out to the model, just in case you're going to be redirecting or doing something else which might end up at another Controller.
The "solution" (and I didn't like it much, but it worked) was to omit the #SessionAttributes annotation on the controller, add an HttpSession parameter to the necessary methods and "manually" manage what's in it.
I'm interested to see if there's a better way, because it seems #SessionAttributes has tremendous potential to tidy up controller-level code.
I registered a WebArgumentResolver to get to my session variable. This allowed me to keep this session variable out of the response while keeping my action unit testable.
Along with #ModelAttribute, pass #ModelMap as a method argument.
Based on business logic, error conditions -- if you do not need the attribute for certain scenarios, then remove it from the map.
public ModelAndView foo(#ModelAttribute("userContext") UserContext, #ModelMap map){
if(success){
return success.jsp
}
else{
map.remove("userContext");
return "error.jsp"
}
}
Not totally satisfied with having to pass the ModelMap as well, but I did not find any other easier way of doing it.
Cheers!!