Can I modify response content before the formatter processes it? - asp.net-web-api

I have an ASP.NET Web Api 2.2 project where I would like to take the response from all controllers and wrap it in a wrapper object with some metadata. Then I would like my custom Media Type formatter (particularly my custom JsonMediaTypeFormatter) to use that extra metadata to do some custom serialization.
I tried creating a DelegationHandler to do the wrapping, but that happens after the formatter in the pipeline. Is there another way to intercept the response from all controller actions, wrap the response in another object and then have the custom JsonMediaTypeFormatter process it?

Have You tried using an ActionFilterAttribute where you can override the OnActionExecuting/OnActionExecuted methods to process/generate the action response using the actionContext.
Have a look into this good article.
Also look at this question.
Hope that helps.

Related

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 debug Web API model binding

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

Access request parameters from a JSP View in Spring Web MVC without putting them in a model

I'd like to be able to access some HTTP GET parameters directly in a JSP, without having to pass them through a Controller+Model, but at the same time still use the dispatcher/controller/model/view mechanism for other parameters and logic.
This is because I have many HTTP GET parameters that are generated by Javascript and used also only in Javascript. My Controllers don't need them at all.
I tried ${arg}, ${request.arg}, ${requestScope.arg}, nothing seems to work.
If I bypass the dispatcher, ${requestScope.arg} works.
But is there a way to make it work with the dispatcher?
Thanks!
If that's request parameters that you want to access (and not request attributes like the title says), then the syntax is ${param.parameterName}.
If it's request attributes, then it's ${requestScope.attributeName}.
See http://java.sun.com/products/jsp/syntax/2.0/syntaxref207.html#1010522 for a quick reference.

Right way to consume a Web Service in WP7

I have a Web Service like ServiceA.asmx. What is the right way to consume it?
I have two ways to consume a service:
1)adding Service Refernce:
I have added Service Refernce of ServiceA.asmx ( Like in http://microsoftfeed.com/2011/part-14-how-to-consume-a-web-service-in-windows-phone-7) and i am able to call the Functions in Service like in the link i have given. If we use this way there is no need to parse the Result, Result returned in Objects(easy to use).
2)Hitting the URL and Calling asynchronously:
Here we can hit the URL, that function will call the asynchronous function that asynchronous function will return the response. But here response will be in XML here we have to parse that XML in to an Object.(not easy if any Big XML is there)
Please Guide me on this
Personally I would use the 'Add service reference' option. It's easy to use, and this option is added to Visual Studio especially for consuming web services. You can still use MVVM to build up your models/viewmodels.
I don't have the option to check it right now, but from my head the classes generated when adding the service reference also implement INotifyPropertyChanged. So you could probably use the object directly (if they are in the structure as you want to use it.) as your Model. Based on that model you can create your own ViewModel which you can bind to the UI.
To see how this works have a look at the code samples on MSDN:
Implementing the Model-View-ViewModel Pattern in a Windows Phone Application
Weather Forecast Sample

Generating urls from MVC Routes in a Management layer...

So... I have a business object/manager which is going to generate emails.
These emails will contain links to various content on the website... and therefore needs to understand about MVC routing.. or at least how to generate URLs for the website...
However my business object will not have access to a RequestContext etc and the email generation is not necessarily the result of a web request to a website (I have a dispatcher which runs on a background thread which will be generating the emails)
Any ideas how I can generate my urls without having access to a request - and therefore being unable to use URLHelper...
Thoughts?
In order to get at the UrlHelper outside of the controller, you need to feed it and the routing data the HttpContext. Here's an example:
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
UrlHelper helper = = new UrlHelper(new RequestContext(context, RouteTable.Routes.GetRouteData(context)));
I prefer to define schema and make both routing and business logic aware of it. Means different implementations of the same URL schema.
Some reasons why:
Your routing mechanism could change. For example in feature you can switch to url_rewrite module.
Possible issues with load-balanced installation.
You do not need even to try to use URLHelper in undocumented way.
BTW, you can replace HttpRequest from URLHelper easily. We used to use this for unit-testing. For more information just search for unit testing of the HttpContextBase or look at examples in source code of the MvcContrib. This can help to instantiate URL helper and all related stuff in non hosted environment. But I still do not think that this is a good idea.
In ASP.NET MVC5 (and possibly MVC4 - I'm not sure when it was introduced), you can do this more directly using HttpRequest.RequestContext. Eg:
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

Resources