Service Stack IRequiresHttpRequest Pattern - servicestack

How does this work? I've read the docs but am hoping for some more info.
From reading the docs I understand that when my DTO implements IRequiresHttpRequest, then the DTO's properties will not get automatically populated, but in my DTO I now have access to the HttpRequest object so I can change my DTO to have 'get' properties that pull things from the request object.
What is meant to inject the HttpRequest into my DTO? The docs suggest that service stack does this behind the scenes, however I can only get it to work if I register a custom request binder and manually inject the HttpRequest object.
RequestBinders.Add(typeof(MyDto), httpReq => {
var dto = new MyDto();
dto.HttpRequest = httpReq;
return dto;
});
Question 1: How exactly is the injection for IRequiresHttpRequest meant to work?
Question 2: Is there a way to gain access to the HttpRequest object so that my DTO can support custom 'get' properties, by still have service stack run it automatic mapping? For example:
public class MyDto
: IRequiresHttpRequest
{
public Int32 AutoMappedProperty1 { get; set; }
public Int32 AutoMappedProperty2 { get; set; }
public Int32 AutoMappedProperty3 { get; set; }
public Int32 AutoMappedProperty4 { get; set; }
public Int32 CustomMappedProperty { get { return customMappedProperty; } }
IHttpRequest httpRequest;
public IHttpRequest HttpRequest
{
get
{
return httpRequest;
}
set
{
httpRequest = value;
// lets say this searches the query string for a variety of
// different keys, and then maps one of them of
// CustomMappedProperty based upon a specific set of rules
customMappedProperty = [...]
}
}
}
In the case above I am defining how CustomMappedProperty gets populated, but I still want service stack to go ahead and map all of the 'set'-able properties. Is there a way to achieve this? Can I manually invoke the service stack dto mapper?

Which docs did you read about IRequiresHttpRequest? IRequiresHttpRequest works the same as IRequiresRequestContext which is only for decorating on Services and Validators to tell ServiceStack that it requires access and to inject the current IHttpRequest or IRequestContext.
The Custom Serialization / Deserialization wiki only mentions that IRequiresRequestStream and IRequiresSoapMessage can be used on Request DTOs to signal to ServiceStack to skip processing the Request body and allow you to manually deserialize the request yourself.

Related

Change Autoquery return type in DTO generation

I want to return a custom class from my custom AutoQuery endpoint that inherits QueryResponse<T> but adds a few extra properties.
public class WritingAssignmentBlogLookUpResponse : QueryResponse<BlogDto>, IResponse
{
public bool Success { get; set; }
public string Message { get; set; }
public string DebugMessage { get; set; }
}
But if I specify request like so:
[Route("/assignment/blogs/", "POST")]
public class WritingAssignmentBlogsLookUpRequest : QueryDb<Blog, BlogDto>, IReturn<WritingAssignmentBlogLookUpResponse>
{
}
Then the return type specified in generatd DTO for client.post(req) is QueryResponse<BlogDto> and it doesn't generate WritingAssignmentBlogLookUpResponse at all.
Do I just have to specify return type as any from my typescript service or is there a way to make the types match so I can strongly type it?
You can’t change AutoQuery responses which are already fixed in their service contract definition to return a QueryResponse<T>.
You can add extra info to the Meta Dictionary of the Response DTO (exists for this reason) otherwise if you need to change the Service Contract you’d need to convert it into a normal (I.e. non-AutoQuery) API which could use the Service Gateway to call an existing AutoQuery API that decorates the response.

Why does ServiceStack burden the DTOs with routing concerns?

I'm learning ServiceStack, and from reading this page, a couple of things aren't clear to me.
So, considering this DTO pair:
[Route("/hello")]
[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
And this service:
public class MyService : Service
{
public object Any(Hello request)
{
return new HelloResponse { Result = $"Hello, {request.Name}!" };
}
}
Why is it the responsibility of Hello to specify the return-type using the marker interface IReturn<HelloResponse>?
It seems like this could be inferred from the return-type of MyService - except that it's conventional to use a return-type of object, which also requires type-casts in tests and client-code. Why?
And why are the Route attributes applied to the model Hello, rather than to the service MyService, where the request is actually handled?
It seems like both of these facts are more relevant to the service than to the model.
For one, a person reading the service declaration would more readily find the information pertaining to the service, instead of having to find it in the model.
For another, accepted HTTP methods are implicitly declared by the service via method-naming conventions - so it seems like the facts about service routing/dispatch are sort of scattered between two layers.
From that point of view, I was probably expecting something more along the lines of this:
// NON-VALID EXAMPLE
public class Hello
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
public class MyService : Service
{
[Route("/hello")]
[Route("/hello/{Name}")]
public HelloResponse Any(Hello request)
{
return new HelloResponse { Result = $"Hello, {request.Name}!" };
}
}
What is the reason or the design thinking behind the conventions?
(Please don't take this as merely an attempt at critique - there's a lot of things I enjoy about this framework, and I am genuinely trying to understand the thinking behind these conventions.)
Why does ServiceStack burden the DTOs with routing concerns?
Note no routing concern burden is required at all in ServiceStack and all user-defined Routes are optional where all clients are able to call Services utilizing their automatic pre-defined routes.
Why is it the responsibility of Hello to specify the return-type using the marker interface IReturn?
It provides better typed access for client libraries like the generic C#/.NET Service Clients who are able to re-use the existing SericeModel DTOs to enable its optimal typed API without any code-gen, e.g:
var client = new JsonServiceClient(baseUrl);
var response = client.Get(new Hello { Name = "World" });
Or if you're not sharing DTOs it's also useful for Add ServiceStack Reference generated clients as well.
The return type on your Service implementation is meaningless in ServiceStack, i.e. has no behavioral difference, and would prevent the same Service implementation from returning the same Response DTO, or decorated with a custom HTTP Response, e.g:
public object Any(Hello request)
{
return new HelloResponse { Result = $"Hello, {request.Name}!" };
//...
return new HttpResult(new HelloResponse { Result = $"Hello, {request.Name}!" }) {
//... custom
};
}
both return types adhere to the API's IReturn<HelloResponse> contract
It's only useful for calling inter-process Services using the older ResolveService method, but for inter-prcess requests it's recommended to use the Service Gateway instead which also utilizes the type IReturn<T> interface markers for its Typed APIs.
The routes are not an implementation detail, they're apart of your public Service Contract and should be annotated on your DTOs which are used to define your Service Contract.
[Route("/hello")]
[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
public string Name { get; set; }
}
public class HelloResponse
{
public string Result { get; set; }
}
Where they're used by the .NET ServiceStack Clients to send Service Client Requests.
var response = client.Get(new Hello { Name = "World" });
For another, accepted HTTP methods are implicitly declared by the service via method-naming conventions - so it seems like the facts about service routing/dispatch are sort of scattered between two layers.
Please see docs on Routing, the Route definition defines which methods the specific route is active on whilst the most appropriate Service implementation is invoked depending on the Request, e.g:
public object GetJson(Customers request) => ... // ONLY GET JSON Requests
public object Get(Customers request) => ... // All other GET Requests
public object Post(Customers request) => ... // ONLY POST Requests
public object Any(Customers request) => ... // ALL other Requests
What is the reason or the design thinking behind the conventions?
A lot of these issues is trying to blur the explicit typed Service Contract of your APIs and its concrete implementation, in ServiceStack these are distinct explicit concepts where all the information about your public Service Contract should be maintained in your implementation-free ServiceModel project.
Please read the Background Concepts docs to familiarize yourself with ServiceStack's purpose and goals.

How can I bind multiple 'Keys' to a single property on a Service Stack Request DTO

I have a DTO that goes something like this:
public class Request {
public id ASpecificIdentifier { get; set; }
public string PreciseDescription { get; set; }
public string FirstPartOfSomeonesName { get; set; }
}
Whilst I'm happy accepting this as the official 'Input', I would also like to be able to bind them to multiple keys. The reason for this will be serialized to a client in an encrypted JSON object, so I would like to keep the length down.
For example they should also be able to pass:
{
"Id":1,
"Desc":"My Issue",
"Name":"Bob"
}
How can I achieve this? I have looked around at the Attributes supplied but non seem to be able to allow this behaviour?
You could create multiple DTOs for each scenario you allow (set of named parameters). Then in your service you would have to handle each DTO and translate them a common DTO to take action.
Or Another way would be to have a DTO that takes a generic key/value parameter. This will make your DTOs very flexible but you will lose some of the advantages of strong typing.
For Example:
public class Request {
Dictionary<string,string> Properties { get; set; }
}

ServiceStack version 3.9.56 gives NullReferenceException error at metadata json page

I just downloaded ServiceStack with NuGet. Version 3.9.56.
I am trying simple webservice but when i open metadata json page it gives NullReferenceException error.
My service is here:
[Route("/users")]
[Alias("Users")]
public class User
{
[Alias("UserID")]
public int id { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
}
public class UsersService:Service
{
public object Get(User request)
{
var result = new List<User>();
result = Db.Select<User>();
return result;
}
}
There is a known issue that might explain your null reference exception. However, you do not want IReturnVoid, unlike in your other post, so the answer here is not to wait for ServiceStack to be fixed but to improve your DTO's declaration:
Your UsersService implementation is returning a List<User> object for your User request. You can document this in ServiceStack like so:
public class User : IReturn<List<User>>
{
...
}
This may fix the issue you are seeing on the metadata page as ServiceStack now knows the type of response to expect for the User message. There are other benefits to decorating your request DTOs with IReturn:
The typed C# client will be easier to use, as the client can know the type of your response message
The Swagger UI, if you use it, will know about and automatically document the response type

Request DTO map to Domain Model

I have the following Domain Model:
public class DaybookEnquiry : Entity
{
public DateTime EnquiryDate { get; set; }
[ForeignKey("EnquiryType")]
public int DaybookEnquiryTypeId { get; set; }
public string AccountNumber { get; set; }
[ForeignKey("User")]
public int UserId { get; set; }
#region Navigation Properties
public virtual User User { get; set; }
public virtual DaybookEnquiryType EnquiryType { get; set; }
public virtual ICollection<DaybookQuoteLine> QuoteLines { get; set; }
#endregion
}
This is inside of a project named DomainModel. Entity is just a base class which my domain models inherit from, it contains an Id field.
I then have other projects inside my solution called ServiceInterface and ServiceModel. ServiceInterface contains all my services for my application and ServiceModel contains my DTO's and routes etc.. I'm trying to follow the guidelines set out here: Physical Project Structure
My EnquiriesService contains a method to create a new enquiry in my database using a repository:
public void Post(CreateEnquiry request)
{
// Not sure what to do here..
// _repository.Insert(request);
}
My CreateEnquiry request looks like so:
[Api("POST a single Enquiry for Daybook.")]
[Route("/enquiries", "POST")]
public class CreateEnquiry : IReturnVoid { }
As you can see, the CreateEnquiry request object is empty. Do I need to add properties to it to match my Domain Model and then use AutoMapper or something similar to map the fields to my Domain Model and pass that into my repository?
The Insert method on my repository looks like so:
public virtual void Insert(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
DbContext.SaveChanges();
}
Yes. Your Service request, in this case CreateEnquiry needs to have all the properties you need in order to do whatever it is you want to do!
I've seen two different models for Create vs Update:
Use one request objects called, say, SetEnquiry that has a nullable id field. When null and using the POST HTTP verb, it internally creates a new object. And when not null and using the PATCH HTTP verb, it internally updates an object. You can use ServiceStack's implementation of AbstractValidator<T> to add logic such as if POST then id field needs to be null; and if PATCH then id field cannot be null. This will help ensure your data is always as it needs to be.
Create two request objects -- one for Create and one for Update. The Create doesn't even have an id field, and the Update has one and requires it. You can use the same validation technique used above, except applied to each class independently, so you don't need the conditional check of if this verb do this; if that verb do that.
How you map to your data model is up to you. You can use something like AutoMapper or you can use ServiceStack's built-in TranslateTo and PopulateWith methods. I personally take a middle ground: I created my own object extension methods called MapTo and MapFrom that interally call TranslateTo and PopulateWith respectively. Why did I do this? Because then I control those extensions inside my own namespaces and when I need to do special mappings (like a column name doesn't match up, or one object is more complex than the other, or I simply want to ignore a particular column from one of the objects) I simply overload the MapTo and MapFrom with explicit types, giving it higher specificity than the generic methods.
So back to your question specifically. Assuming you're using the built in TranslateTo your service method might look like this:
public void Post(CreateEnquiry request)
{
_repository.Insert(request.TranslateTo<Enquiry>());
}
One more thing: I generally return the object itself when doing a Create and Update. As fields can change (auto-calculated fields, for example) I like to return the object back to the caller. This is preference and has no real bearing on the answer I'm giving you. Just throwing it out there!

Resources