问题
I have a class which contains a property who's type is another class. For example:
public class Outer
{
public string SomeStringProperty { get; set; }
public Inner SomeClassProperty { get; set; }
}
public class Inner
{
public string InnerProperty1 { get; set; }
public string InnerProperty2 { get; set; }
}
I want to convert an instance of the Outer
class to a URL query string, and include the properties from the nested Inner
class.
For example, given an instance of Outer
, such as:
Outer toSerialise = new Outer
{
SomeStringProperty = "MyOuterValue",
SomeClassProperty = new Inner
{
InnerProperty1 = "MyInnerValue1",
InnerProperty2 = "MyInnerValue2"
}
};
I want to convert this to a string of:
&SomeStringProperty=MyOuterValue&InnerProperty1=MyInnerValue1&InnerProperty2=MyInnerValue2
How can I achieve this?
I've found answers to similar questions, however they don't seem to support nested classes.
Potential answer 1 Potential answer 2
回答1:
We had same problem with callback url's client state in Oauth2 because callback urls have ampersand & too
http://.......?param=123¶m2=456&state=?id=1&name=test
We just converted callback url to Base64 encoded string and decoded at service itself.
http://.......?param=123¶m2=456&state=P2lkPTEmbmFtZT10ZXN0
Fix:
- Encode your class instance as json
- Encode json as base64string
- Send base64string in url as data param
- Decode base64 and map json into your model at your api.
JSON:
{ "menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Base64:
eyJtZW51IjogewogICJpZCI6ICJmaWxlIiwKICAidmFsdWUiOiAiRmlsZSIsCiAgInBvcHVwIjogewogICAgIm1lbnVpdGVtIjogWwogICAgICB7InZhbHVlIjogIk5ldyIsICJvbmNsaWNrIjogIkNyZWF0ZU5ld0RvYygpIn0sCiAgICAgIHsidmFsdWUiOiAiT3BlbiIsICJvbmNsaWNrIjogIk9wZW5Eb2MoKSJ9LAogICAgICB7InZhbHVlIjogIkNsb3NlIiwgIm9uY2xpY2siOiAiQ2xvc2VEb2MoKSJ9CiAgICBdCiAgfQp9fQ==
Url:
&data=eyJtZW51IjogewogICJpZCI6ICJmaWxlIiwKICAidmFsdWUiOiAiRmlsZSIsCiAgInBvcHVwIjogewogICAgIm1lbnVpdGVtIjogWwogICAgICB7InZhbHVlIjogIk5ldyIsICJvbmNsaWNrIjogIkNyZWF0ZU5ld0RvYygpIn0sCiAgICAgIHsidmFsdWUiOiAiT3BlbiIsICJvbmNsaWNrIjogIk9wZW5Eb2MoKSJ9LAogICAgICB7InZhbHVlIjogIkNsb3NlIiwgIm9uY2xpY2siOiAiQ2xvc2VEb2MoKSJ9CiAgICBdCiAgfQp9fQ==
Alternative :
If you must use this query format then you can also use delegate types
Outer toSerialise = new Outer
{
SomeStringProperty = "MyOuterValue",
SomeClassProperty = new Inner
{
InnerProperty1 = "MyInnerValue1",
InnerProperty2 = "MyInnerValue2"
}
};
var queryObject = new { toSerialise.SomeStringProperty, toSerialise .Inner.InnerProperty1, toSerialise.Inner.InnerProperty2 }
来源:https://stackoverflow.com/questions/60338449/serialise-an-object-to-url-parameter-string-including-properties-from-nested-o