I have a REST ServiceStack Route.Add declaration like this
Routes.Add<MyDTOObject>(/servicename/{property1fromDTO}); but I need to pass an additional String value that is not defined on MyDTOObject class declaration.
Is it possible to pass something like this Routes.Add<MyDTOObject>(/servicename/{property1fromDTO}/{additionalString}); and retrieve it on my OnGet(MyDTOObject request){...} method implementation?
Currently I'm only able to get values from request for attributes that are defined on the MyDTOObject class declaration as specified by the Annotation used for the Routes.Add.
On my Service code I have this:
public override object OnGet(MyDTOObject request){ ...
request.property1fromDTO //get value
...}
but I cannot do this:
request.additionalString //get the value
because Visual Studio doesn't recognizes it as a property of type MyDTOObject
Help will be appreciated since I'm fairly new to ServiceStack and RESTful services. Thanks!
Not exactly sure what you're trying to achieve but you can use a wildcard at the end to absorb multiple paths, e.g:
Routes.Add("/save/{Year}/{Week}/{DaysString*}");
Which will populate the known variables and leave the rest in DayString for you to parse manually. See this answer for more details.
You can ignore the additional path with the {ignore} keyword, e.g:
Routes.Add<MyDto>(/servicename/{property1fromDTO}/{ignore});
You also have full access to the request from inside a Service with base.Request, e.g:
base.Request.QueryString["param"];
base.Request.PathInfo
base.Request.RawUrl
*Note: it looks like you're using the old API (i.e. OnGet). I recommend inheriting from Service so you can use the New API as the Old API was removed in the next v4 of ServiceStack.*
Related
I have a CodeFix provider, purpose of which to inject service to current class, like add new private field, parameter to constructor, assignment statement in constructor, using ServiceNamespace, and use of this field in proper place(s).
At some point, I have a name of this service, and I need to find namespace for this service to add correct using. I'm doing this via compilation.GetSymbolsWithName(typeName), but this method can return several matched symbols from different namespaces/assemblies.
So, the question: is there any way I can show this variants to user so he can decide the correct type?
For each diagnostic, you can add more than one fix.
i have tried to surf the internet but i could not get anything related to what i want.
This is in relation to ASP.Net. But could be any other instance as well.
Following is my attribute
class SomeAttribute :Attribute
{
string someparam;
string SomeParam
{
get{ return someparam;}
set { someparam = val;}
//the value generated for someparam is dynamically generated with respect to some attribute present in the request header.
}
}
it's similar to the [Authorize] attribute that .net uses in its asp .net memberships to validate if the user has logged in and it redirects him back to log in page if validation fails.
I have an attribute associated with a method like below:
[SomeAttribute]
public void someFunction
{
//i want to retrieve here the value of someparam jus generated before entering this method.
}
Note that i don't pass any value or used any named properties in this attribute. It is simply going to check a condition for me whenever the method is called and return true or false and accordingly the function is either called or not.
In my case, After validating, it generates a value and that value has to be shared with the function to which it is associated 'somefunction'.
i know reflections can help me get the attributes associated with a function and the value of its properties.
But here i dont want to fetch the value from some other function. And i dont want to just fetch the attribute either.
As i mentioned earlier when the function is called the attribute will work upon that. What the attribute does is fetches some data from request header and does some processing and generates a value. Now this value has to be passed on to the function just after that.
Well, what you want to accomplish is certainly possible, but it would not be an optimal use of the run-time or the MVC model.
In this particular case, think of an attribute as an annotation. It's something you use to mark a function, controller, etc. so that its execution behaves differently at run-time. The attribute itself should not be doing the bulk of the work, rather just signalling to other pieces in your design to behave differently.
It seems like you want to check some header values, and calculate something based off of that. You can use extension methods off of a Request class to accomplish this.
Now, let's say that inside your Controller's function, you want to guarantee that the header values exist. You can have an attribute called RequireHeaderValues that implements IActionFilter. The attribute would check the header for the required values and if they don't exist, it routes the response to another location or somehow indicates error. This way, when inside your function, you call the extension method off the Request object, you are guaranteed that the values will exist. The MVC run-time will automatically call your filter attribute for you. For more info, see this.
I have a small WinRT client app to my online service (Azure Web Service). The server sends a JSON encoded object with (with potential additional metadata) to the client and the client's responsibility would be to deserialize this data properly into classes and forward it to appropriate handlers.
Currently, the objects received can be deserialized with a simple
TodoItem todo = JsonConvert.DeserializeObject<TodoItem>(message.Content);
However, there can be multiple types of items received. So what I am currently thinking is this:
I include the type info in the header serverside, such as "Content-Object: TodoItem"
I define attributes to TodoItem on the client side (see below)
Upon receiving a message from the server, I find the class using the attribute I defined.
I call the deserialization method with the resolved type
(Example of the attribute mentioned in 2.)
[BackendObjectType="TodoItem"]
public class TodoItem
My problem with this approach however is the Type to Generics in the deserialization as I can't call:
Type t = ResolveType(message);
JsonConvert.DeserializeObject<t>(message.Content);
I tried finding some solutions to this and getting method info for the DeserializeObject and calling it using reflection seemed to be the way to go. However, GetMethod() does not exist in WinRT and I was not able to find an alternative I could use to retrieve the generic version of the DeserializeObject (as fetching by the name gives me the non-generic overload). I don't mind using reflection and GetMethod as I can cache (?) the methods and call them every time a message is received without having to resolve it every time.
So how do I achieve the latter part and/or is there another way to approach this?
Alright, I feel like this was not really a problem at all to begin with as I discovered the DeserializeObject(string, Type, JsonSerializerSettings) overload for the method. It works splendidly. However, I would still like to hear some feedback on the approach. Do you think using attributes as a way to resolve the type names is reasonable or are there better ways? I don't want to use the class names directly though, because I don't want to risk any sort of man-in-the-middle things be able to initialize whatever.
Just a few minutes ago we have posted the alternative way to do what you want. Please look here, if you will have any questions feel free to ask:
Prblem in Deserialization of JSON
Try this
http://json2csharp.com/
Put your Json string here it will generate a class
then
public static T DeserializeFromJson<T>(string json)
{
T deserializedProduct = JsonConvert.DeserializeObject<T>(json);
return deserializedProduct;
}
var container = DeserializeFromJson<ClassName>(JsonString);
I have a requirement for users to edit a list of quotes for a lead, the quotes can be different types such as:
QuoteForProductTypeA
QuoteForProductTypeB
All quote types share a common base class, such as QuoteBase.
I have my quotes displaying fine on the front end, and appear to post back the correct data too.
However, on the server it doesn't obviously doesn't know which subclass to use, so just uses the base class.
I think i need some kind of custom model binder for WebApi to check for a hidden field such as ModelType which contains the type of the object in the collection, the model binder then creates a new object of this type and binds the properties from my posted values to this object.
However, i am stuck at this point with very little documentation / blogs on how to do this.
I have checked the source code for WebApi to see if i can extend a default model binder, but any defaults are sealed classes.
I can only implement IModelBinder by the looks of it, i can create the correct model type by looking for a value called ModelType, but then i'm not sure how to fill the rest of the values in my subclasses, if there was a default model binder i was inheriting from i would just call the base classes bind method.
If your post collection comes from request body, it won't go through model binder. Web API will use formatter to deserialize the content.
If you just want to support json, it's quite easy. Just add following code to your web api config:
config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto;
The setting will let json.net to save type name in the payload if the runtime type is different with the declare type. When you post it back, json.net will deserialize the payload to the type you specified in the payload.
A sample payload looks like:
{"$type":"MvcApplication2.Models.Car, MvcApplication2","SeatCount":10,"WheelCount":4,"Model":0,"Brand":null}]
I need to check the RequestType of an HttpRequest in ASP.NET (or WebRequest.Method). I know that I can just use the string values "POST" or "GET" for the request type, but I could have sworn there was a constant somewhere in some class in .NET that contained the values.
Out of curiosity I was wondering if anyone knew what class these string constants for GET and POST were in. I've tried searching online but I've had no luck, so I thought I'd ask here.
System.Net.WebRequestMethods.Http
.Connect = "CONNECT"
.Get = "GET"
.Head = "HEAD"
.MkCol = "MKCOL"
.Post = "POST"
.Put = "PUT"
Ultimately, though; since const expressions are burned into the caller, this is identical to using "GET" etc, just without the risk of a typo.
Also exists System.Net.Http.HttpMethod which can serve instead of enum. You can compare them aMethod == HttpMethod.Get, etc. To get string method name call e.g. HttpMethod.Get.Method.
In ASP.NET MVC they're in System.Web.Mvc.HttpVerbs. But all methods that take one of these enum values also has a text override, as there is no complete set of HTTP verbs, only a set of currently defined values (see here and here and here).
You can't create an enumeration that covers all verbs, as there is the possibility that verbs can be added, and enumerations have versioning issues that make this impractical.
In ASP.NET Core you will find a collection of http method strings in the HttpMethods.cs class under the Microsoft.AspNetCore.Http namespace.
This class also offers boolean helpers such as IsGet() or IsPost() for better semantics.
Please note that these strings are exposed as public static readonly string and not as constants.
UPDATE 2020-05-17: GetCanonicalizedValue(string method) was added to the HttpMethods.cs class in ASP.NET Core v5, which returns the static instance equivalent to the provided string method name.