How to debug Web API model binding - asp.net-web-api

I've been working with quite some Web API projects now and find myself bumping into the same problem every time and that's when I do a POST or GET the value / model etc is null or I get a 404.
There is a checklist like:
- did I use the correct content-type?
- has routing been set up correctly
- is the signature of the model that I'm posting really the same as the model that the endpoint accepts?
It would be nice if there is a trace one could follow where it fails. Now it just looks like a black box, you put something in and it works or not, if it doesn't: see checklists or SO.
Is there something that you can setup in Web API so you can debug the model binding process?

I would implement action filter.
One of the methods that can be overridden there is :
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
In this action you can check the response status and if it is an error to perform all your checks
This article could be a good starting point

Related

Why is my HTTP request URL not being generated for a Logic App?

Good morning. I am new to logic apps and I am trying to figure out how I can trigger the execution based on a GET URL with three parameters. All the examples I've found on Google show the URL being generated once the JSON and relative path is entered, but that's not happening for me. Perhaps it's because I am creating the logic app in VS.
Here's what my "When a HTTP request is received" step looks like in the logic app.
I also tried removing the JSON and just using the parameters to pass the values to the function, as shown below. I'm just not sure the best way to do this.
All I really need to do is get the three parameters into the logic app so I can perform a function call with the parameters. Any suggestions would be greatly appreciated!
Why is my HTTP request URL not being generated for a Logic App?
You need to click save, and then the url will be automatically generated for the When a HTTP request is received trigger:
You can use this expression to accept values through GET parameters:
triggerOutputs()['queries']['parameter-name']
For example:
Noteļ¼š
Queries need to pass parameters in the form of json.

Intercepting incoming client request using ClientHttpRequestInterceptor with RestController

I want to append some data to the incoming request. Like random generated token or uuid to the incoming request. And then I want to process it through the controller. I came to know about ClientHttpRequestInterceptor. But looking at this doc, it seems like it only intercept the response, it doesn't intercept the request. Which is what I am not looking. Is there any other way to do this ?
And how can I register this intercept in my RestController ? So that before controller process the request, the request should already has the data.
EDIT:
I just found out, I can directly set the data in controller using set method in request body. And this is working. But I am not sure if this is recommended way. Because as far as I know the request has to be modified in dispatcher servlet.
Please advice.
If you don't want to do it this way (How to modify request body before reaching controller in spring boot),
you might do one of the following:
OncePerRequestFilter (as mentioned in the #doctore answer) and add a parameter to the request. This would allow you to add data to the request, but not change anything sent by the client.
Add a method in the controller and call it at the start of processing. I don't like this as much because unlike the filter approach, this requires you to call the method.
[Note: I've never tried this, but it should work] Add a method [somewhere] and use Spring AOP to call it before entering the handler method in the controller. This is fine, but is essentially just you creating your own way of processing a OncePerRequestFilter.
There are surely other ways of doing this with Spring,
I just don't know them.
You need to add your own OncePerRequestFilter implementation. In the next link you will be able to see an example of that:
Filter example
In this case, it uses TheadContext (MDC) to include the information you want to use in your controller layer (do not include "something similar" to MDC.remove(mdcTokenKey); in your code, you want to keep the information on MDC to access it in your controller).
PD: The internal server of Spring MVC: Tomcat, Jetty, etc reuses the threads so, if you don't want to have some problems it is important you include always a value in your "TheadContext cache". In that way, you will avoid to find "old values", I mean, values included in the current thread but in a "previous Http request".
UPDATE (modify the request body):
Take a look to the following link if you want to modify the request itself:
Modify request content before manage it in controller

How to stop grails erasing custom validation errors

In my Grails app, I am using methods in a service to do complicated validation for user submitted data. Unfortunately, Grails is quietly sabotaging me.
I populate the domain instance with the user submitted data
I hand the instance off to the service, which analyzes the properties.
If errors are found I add them using
instance.errors.rejectValue('myValue','errors.customErrorCode','Error')
BEHIND THE SCENES, when the service passes the domain instance back to the controller grails checks for changed properties and calls validate() before returning the instance. (verifiable by seeing the beforeValidate event called on returning a domain instance from a service to a controller where one or more properties has changed)
That behavior clears any custom errors I have added and the instance I get back in the controller is now incorrectly without error.
How can I
A) stop grails from validating between service and controller
OR
B) prevent a validate() call from wiping my custom errors.
EDIT
So far I've found one partial answer,
If you use instance.get(params.id), grails will self validate behind the scenes wiping custom errors.
If you use instance.read(params.id) you can bypass this behavior to an extent.docs
But this solution is limited by domain relationships. Any other solutions welcome.
Seems that it is not custom validation. It can be because of transactional service. Service opens separate transaction for each method and clears entities after method end. You can find this mentioned in docs(read the last paragraph of part ). So errors dessappear not because of validation.
Don't know if your service is transactional. But if it is - you can add #NotTransactional annotation to method were you want not to loose errors. And
errors will be saved.
Hope it helped,
Matvei.
Not sure how your code looks like or what is causing the problem, but in any case I strongly suggest implementing custom validators in the domain class or in a command object within the constrains.
Here are some examples from grails docs:
http://docs.grails.org/2.4.0/ref/Constraints/validator.html

DRY Remote Validation in ASP.NET MVC 3

I've read David Hayden's great post on MVC 3 Remote validation.
However there is presented what you should do to enable remote (javascript) validation. If the user has javascript disabled the post would still be made even if data is not valid. Therefore a server-side validation should occur.
How could we make this check as DRY (Don't Repeat Yourself) as possible? Of course, including the same check code in the post action as in the remote validation action (or just the same call) can work but I am wondering if a one-liner or something more elegant is available.
Perfectly acceptable answers include "no, it can't be done". :)
See my MSDN article How to: Implement Remote Validation in ASP.NET MVC
I use the remote client validation code in the HttpPost Create method to test server side when JavaScript is disabled.
[HttpPost]
public ActionResult Create(CreateUserModel model) {
// Verify user name for clients who have JavaScript disabled
if (_repository.UserExists(model.UserName)) {
ModelState.AddModelError("UserName", ValidationController.GetAltName(model.UserName, _repository));
return View("Create", model);
}
It 'can' be done.. but you would need to write your own custom attribute that basically emits for client side and is validated server side. For me I just extract the validation code into a method and check on the server.
Something similar came up recently as well:
Prevent form from submitting when using unobtrusive validation in ASP.NET MVC 3
I wonder if one couldnt inherit from the remote attribute and add their own server side code them. hmm.. maybe I'll have to try this.
I would be happy though if someone here said they already did this : )
I have done this, it's a bit of a long solution, so it's all available on my blog here:
http://www.metaltheater.com/tech/technical/fixing-the-remote-validation-attribute/
I had to create a new subclass of the RemoteAttribute class, create my own custom model binder by inheriting from DefaultModelBinder, and then use reflection to call the validator on the controller.

ASP.NET MVC 3, RavenDB, & Autofac Issue Plus 2 Other Autofac Questions

NOTE: There are 3 questions in here and I did not make separate questions since they are all somewhat related to the same code.
I have the following code that registers the connection to my RavenDB in the Application_Start once per the application's life cycle:
var store = new DocumentStore { Url = "http://localhost:8080" };
store.Initialize();
builder.RegisterInstance(store).SingleInstance();
Now this works fine and this is something that should be created only once per the application's life cycle. Now I wanted to add in the DocumentSession to Autofac so I tried to add in this in the Application_Start:
var session = store.OpenSession();
builder.RegisterInstance(session).SingleInstance();
In my UserRepository I have the following constructor:
public UserRepository(DocumentStore store, DocumentSession session)
When I try to run this, I get the follow runtime error:
Cannot resolve parameter 'Raven.Client.Document.DocumentSession Session' of constructor 'Void .ctor(Raven.Client.Document.DocumentStore, Raven.Client.Document.DocumentSession)'
That error to me sounds like Autofac does not think it has a DocumentSession however that is what store.OpenSession() returns so it should. Anyone know what would be causing this error? Am I not setting the session variable correctly (it is the same as the store variable which works fine)?
Another thing which may or may not be related to the above issue is how do I add an instance of an object to Autofac per request instead of per the applications life cycle? While the RavenDB DocumentStore object should only be created once be the life application cycle, the DocumentSession should be created once per the request (maybe creating it per application level is causing the error above).
One last question I will throw there about Autofac (mildly related to the code above) is about releasing the objects. If you take a look at this tutorial:
http://codeofrob.com/archive/2010/09/29/ravendb-image-gallery-project-iii-the-application-lifecycle.aspx
The last piece of code:
ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
and the point of this code is to prevent leaking the sessions. Now is this something I also need to worry about for Autofac and if so, how would I do this in Autofac?
I'm guessing you want something like:
builder.Register(c => c.Resolve<DocumentStore>().OpenSession()).InstancePerLifetimeScope();
"The default ASP.NET and WCF integrations are set up so that InstancePerLifetimeScope() will attach a component to the current web request or service method call." - Autofac: InstanceScope
Basically, in a web app, InstancePerLifetimeScope handles the one per HTTP context aspect, and also disposes any types that implement IDisposable.
There was also the issue that OpenSession returns a IDocumentSession instead of a DocumentSession. Changing my class to look for a IDocumentSession along with doing what Jim suggested worked, thanks.

Resources