I am using axios get method and passing params to asp.net mvc controller. I can read individual values. But I am trying to read all values together as one object. I do not have a view model and I am trying to read params as generic object. What will be axios params datatype to use in c# controller as parameter ? I created a seperate method for buildurl and validating each parameter but is there any option to validate all at once?
This works
React Code
export const GetRequestCall = () => {
const getUrl = 'baseurl';
return new Promise((resolve, reject) => {
axios.get(getUrl, {
params: {
param1: 'abc',
param2: 'efg'
}
})
.then(response => {
}).catch(error => reject(error));
});
};
C# controller code
//Read parameter as individual strings
[HttpGet("[action]")]
public async Task<string> GET(string param1, string param2)
{
try
{
var url = BuildUri( param1, param2);
}
}
This did not work
Controller code
//Read parameters as a single object to do some logic. Tried
//[FromBody]object, Object, String as parameters datatypes for data
[HttpGet("[action]")]
public async Task<string> GET(Array data)
{
try
{
var url = BuildUri( param1, param2);
}
}
private static string BuildUri(string BaseUrl, string param1, string param2)
{
var uriBuilder = new UriBuilder(BaseUrl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
if (!string.IsNullOrEmpty(param1)) { query["param1"] = param1; }
if (!string.IsNullOrEmpty(param2)) { query["param2"] = param2; }
uriBuilder.Query = query.ToString();
var url = uriBuilder.ToString();
return url;
}
I found option to build query string with name value pairs in C# but not sure on how to pass axios params as name value pair object to c# controller. Ref: https://codereview.stackexchange.com/questions/91783/constructing-a-query-string-using-stringbuilder
There are probably better ways to do it, but one way is to use an object[] parameter like this:
[HttpGet("[action]")]
public string GET(object[] objects)
{
string param1 = objects[0] as string;
string param2 = objects[1] as string;
try
{
var url = BuildUri(param1, param2);
}
}
Also you should not use try blocks without catch blocks. I hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With