QueryString.Add() gives "Specified method is not supported." - servicestack

I am trying to modify the query string in a request filter like so:
public override void Execute(IRequest req, IResponse res, object requestDto)
{
req.QueryString.Add("foo", "bar");
}
Bust ServiceStack throws error:
Specified method is not supported
It seems that it is read only. How can I modify query string in a filter?

You can't modify the request which is immutable, you can add any per request items you want to attach to the request in IRequest.Items or you can update the dto Request DTO.

Related

Trying to implement a custom route in umbraco 7.5.3 but the overrided method FindContent does not get fired

I've trying to retrieve the rendermodel model into my custom hijacked method, but i always get null. The two optional parameters are correct.
This is my custom route :
RouteTable.Routes.MapRoute(
"umbracoRoute",
"token-verification/{action}/{userId}/{code}",
new
{
controller = "ExternalLinkOperations",
action = "",
userId = UrlParameter.Optional,
code = UrlParameter.Optional
},
new ConfirmEmailRouteHandler(3290)
);
this is the ConfirmEmailRouteHandler class:
public class ConfirmEmailRouteHandler: UmbracoVirtualNodeByIdRouteHandler
{
public ConfirmEmailRouteHandler(int realNodeId) : base(realNodeId)
{
}
protected override IPublishedContent FindContent(RequestContext requestContext, UmbracoContext umbracoContext, IPublishedContent baseContent)
{
return base.FindContent(requestContext, umbracoContext, baseContent);
}
}
and this is the the method in the ExternalLinkOperationsController which inherit from rendermodel:
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(RenderModel model, string userId, string code)
{}
so Im not getting the model parameter only the two optional parameter, what i could be doing wrong, I also tried to make this
new UmbracoVirtualNodeByIdRouteHandler(3290)
instead of
new ConfirmEmailRouteHandler(3290),
but without success, I'm using umbraco v 7.5.3. Debugging the code in any moment the overrided method FindContent gets fired, only when the constructor.
Thanks in advance for any help
I didn't realized the route property is incorrect, i have RouteTable.Routes.MapRoute, and i am supposed to be using RouteTable.Routes.MapUmbracoRoute
answer by Shannon Deminick here!

How to execute servicestack request validation code only

I'm wondering is there a way to flag to servicestack that you only want to execute the fluent validation filter for a request, and not go on to run the real code?
Ideally you could add a property to any request, something like
`ExecuteValidationOnly = true`
This would be really useful for tests, and for validating forms client side.
Thanks.
There's no such feature built into ServiceStack, but you can easily add a Request Filter that short-circuits the request based on a QueryString, e.g:
public class SkipRequestFeature : IPlugin
{
public void Register(IAppHost appHost)
{
appHost.GlobalRequestFilters.Add((req, res, dto) => {
if (req.QueryString["SkipRequest"] == "true")
res.EndRequestWithNoContent();
});
}
}
And register the plugin just after the ValidationFeature so it's executed after validation, e.g:
Plugins.Add(new ValidationFeature());
Plugins.Add(new SkipRequestFeature());
For this case, I usually unit test my actual AbstractValidator<T> class then when I need to test the service I create a mock on the validator and setup validation calls.
So there is a MyValidatorTests class and a MyServiceTests class.

JAX-RS 2 and Jersey 2 : how to pass an (hash)map on a GET request

I simply want to pass an map to my #GET method on my web services using JAX-RS 2. I want to know if it's possible and how to make it, even if GET's methods don't have any body.
Like this :
#GET
#Path(??)
#Produces({"application/xml", "application/json"})
public User find(#PathParam(??) HashMap<String, String> map) {
// work on map !
}
I've seen that it existed the MultiValued map but it's for the parameters. How to pass an map please ?
Thanks by advance !
You will need to have Jackson jars in your classpath (or any other XML / JSON to Map mapper)
You probably don't want to pass the map on the #PathParam, for aesthetical, convention and security reasons. You usually pass a JSON / XML object as the request body, e.g. using a POST / PUT
#POST
#Path("/anypath")
#Consumes({"text/xml", "application/json"})
public User find(HashMap<String, String> map) {
//magic should happen
}
Then just pass a POST / PUT request with content type application/json or text/xml that has
e.g.
{
"key1": "value1"
"key2": "value2"
}
If you have the right Jackson / Moxy etc mapper in the classpath, it will do the conversion between the JSON / XML format to a java.util.Map (or even a POJO) for you
The #Produces is only needed if you intend to also return XML / JSON, but since you are expecting either XML or JSON, then having a #Consumes makes sense here.
However, if you must pass the JSON object on a GET request, e.g. as a request param, take a look at this question: Convert JSON query parameters to objects with JAX-RS
p.s. for xml the mime is text/xml and not application/xml
Get comfortable with #Context.
#GET
public Response superSpecialSearch(#Context UriInfo info, #Context HttpHeaders headers, #Context SecurityContext securityContext) {
var iAmAMutivalueMap = info.getQueryParameters(true);
var searchResults = searchForThings( iAmAMultivalueMap );
return Response.ok(searchResults )
}

ServiceStack - Request Binding JSON encoded parameter

I have an existing application that sends a Request with a parameter named 'filters'. The 'filters' parameter contains a string that is JSON encoded. Example:
[{"dataIndex":"fieldName", "value":"fieldValue"}, {"dataIndex":"field2", "value":"value2"}].
Using ServiceStack, I would like to bind this as a property on a C# object (class Grid). Is there a preferred method to handle this? Here are the options I can think of. I don't think either 'feel' correct.
Option 1:
I do have a 'ServiceModel' project and this would create a dependency on it which I don't really like.
In AppHost.Configure() method add
RequestBinders[typeof(Grid)] => httpReq => {
return new Grid() {
Filters = new ServiceStack.Text.JsonSerializer<IList<Filter>>().DeserializeFromString(httpReq.QueryString["filters"])
}
}
Option 2:
Seems kind of 'hacky'
public class Grid
{
private string _filters;
public dynamic Filters {
get
{
ServiceStack.Text.JsonSerializer<IList<Filter().DeserializeFromString(_filters);
}
set
{
_filters = value;
}
}
}
You can send Complex objects in ServiceStack using the JSV Format.
If you want to send JSON via the QueryString you can access it from inside your Service of Request filters with something like:
public object Any(Request req) {
var filters = base.Request.QueryString["Filters"].FromJson<List<Filter>>();
}
Note: Interfaces on DTOs are bad practice.

allow requests from specific url

I have controller
public class BilingController : Controller
{
…
[HttpPost]
public string Result (string data)
{
…
}
…
}
Method Result can be caused only by foreign service process.anypayservice.com
How can I check url, is request from service process.anypayservice.com or other service?
Or allow only this url - process.payservice.com for method Result call
Any attribute or I should write custom?
You can check the HTTP_REFERER header, but note that it can be easily spoofed.
A better approach is to use some sort of token that can be passed in to your service for authentication.

Resources