Reading Axios Get params in Asp.Net MVC controller - c#

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

Related

Correct syntax of dynamic return type ActionResult<T> use by explicit ActionResult<Contact> and others

I have the following code, would like to create dynamic return type of ActionResult of function getResponse, so it can be used as a generic function for all other models like ActionResult.ActionResult etc etc.
The reason I am having an explicit return type is because it needs to be working with Swashbuckle openAPI
which response can be in XML, Json, Text...
and it looks like it only works by using ActionResult
What is the correct syntax of public async Task> getResponse(HttpResponseMessage results)??? Thanks, guys.
public async Task<ActionResult<Contact>> Get(string referenceId = "af2f8f37-c1d9-40d3-9f29-08d5dab10621")
{
Settings.ReferenceID = referenceId;
//same as get a single Contact;
var url = Settings.PutContactUrl;
Log.Information($"Endpoint hit: {url}");
var requestData = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
};
var results = await _client.SendAsync(requestData);
return getResponse(results);
if (!results.IsSuccessStatusCode)
return StatusCode((int)results.StatusCode, JsonConvert.DeserializeObject(results.Content.ReadAsStringAsync().Result));
//need to cast type to provide xml result
var contact = JsonConvert.DeserializeObject<Contact>(results.Content.ReadAsStringAsync().Result);
//var abc = _mapper.Map<Contact>(contact);
return StatusCode((int)results.StatusCode, contact);
}
[NonAction]
public async Task<ActionResult<T>> getResponse(HttpResponseMessage results)
{
if (results.IsSuccessStatusCode)
{
switch (results.StatusCode)
{
case HttpStatusCode.NotFound:
return StatusCode((int)results.StatusCode, results.Content.ReadAsStringAsync().Result);
default:
return StatusCode((int)results.StatusCode, JsonConvert.DeserializeObject(results.Content.ReadAsStringAsync().Result));
}
}
return StatusCode((int)results.StatusCode, JsonConvert.DeserializeObject(results.Content.ReadAsStringAsync().Result));
}

I want to use an out parameter with string variable

I want to use an out parameter with string variable.
For Example:
string Url = "https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier"
string BaseUrl = this.DecompositionUrl(out Url).BaseUrl;
string ServiceUrl = this.DecompositioUrl(out Url).ServiceUrl;
I want to using a method like this.
public static string DecompositionUrl(out string Urlr)
{
// enter here :
BaseUrl = Urlr.Substring(0,40);
ServiceUrl = Urlr.Substring(40,Urlr.Length);
}
When returned my DecompositionUrl I want to set BaseUrl and ServiceUrl
You need to declare out parameters for the two values that you intend to return from your method: baseUrl and serviceUrl. The source url needs to be passed in through an ordinary parameter (not out).
public static void DecompositionUrl(string url, out string baseUrl, out string serviceUrl)
{
baseUrl = url.Substring(0, 40);
serviceUrl = url.Substring(40);
}
You would then call your method like so:
string url = "https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier"
DecompositionUrl(url, out var baseUrl, our var serviceUrl);
Console.WriteLine($"Base URL is {baseUrl} and service URL is {serviceUrl}.");
C# 7 allows you to return a 'tuple' as the result of a method like this
public static (string, string) DecompositionUrl(string url)
{
var baseUrl = ...;
var serviceUrl = ...;
return (baseUrl, serviceUrl);
}
You can then use it like this
(string baseUrl, string serviceUrl) = DecompositionUrl("https://learn.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-parameter-modifier");
I think that's better than using the out keyword since it's clearer what's input and what's output.

Pass list of strings from client to web api

The client application accesses a web api controller to get a set of data , the controller has a list as parameter.
static void Main(string[] args)
{
Program p = new Program();
p.getdata().Wait();
}
public async Task getdata()
{
List<string> datelist = new List<string>();
datelist.Add("12/05/2017");
datelist.Add("14/05/2017");
datelist.Add("18/05/2017");
HttpClient host = new HttpClient();
host.BaseAddress = new Uri("http://localhost/widgetApi/");
host.DefaultRequestHeaders.Clear();
host.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
StringContent content = new StringContent(JsonConvert.SerializeObject(datelist), Encoding.UTF8, "application/json");
HttpResponseMessage response = await host.GetAsync("api/dataAccessApi?"+ datelist);
response.EnsureSuccessStatusCode();
if( response.IsSuccessStatusCode)
{
Console.Read();
}
}
The controller is
public HttpResponseMessage Get([FromBody] List<string> dates)
{
..... function going here
}
My question is how can I pass datelist to the web api ??
GET requests do not have a BODY, you can use query string values. ?dates='{UrlEncoded date}'&dates='{UrlEncoded date}'...
public HttpResponseMessage Get([FromUri] List<string> dates) {
//..... function going here
}
On the client side you would need to construct the query string and append it to the Uri
var dates = datelist.Select(d => string.Format("dates={0}", UrlEncode(d));
var query = string.Join("&", dates);
var uri = "api/dataAccessApi?" + query;
With UrlEncode looking like this
/// <summary>Escape RFC3986 String</summary>
static string UrlEncode(string stringToEscape) {
return stringToEscape != null ? Uri.EscapeDataString(stringToEscape)
.Replace("!", "%21")
.Replace("'", "%27")
.Replace("(", "%28")
.Replace(")", "%29")
.Replace("*", "%2A") : string.Empty;
}
For Asp.Net Core consider to use [FromQuery] instead of [FromUri]

Api lost lost param

Hi I have this code to run my api method
export class MessageService {
constructor(private http: Http) {
}
addMessage(textToSend: string) {
return this.http.post("/api/SendMessage", textToSend); //<- Everytime i have some text in textToSend and this is ok
}
}
And after in my Api my param is equals to null
[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage(string msg) //null value
{
//some code
}
Your controller action is accepting a query parameter, not a router parameter or model.
If you want to accept a route parameter, you need to add it to the route.
If you want to pass a model or value in the body, you must mark the parameter with [FromBody] attribute.
[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage([FromBody]string msg)
{
MessageBox MsgBox = new MessageBox();
MsgBox.AddMsgToMsgBox(msg);
}
If you don't define anything, the controller expects the parameter to be passed as query /api/SendMessage?msg=someMessage (which you shouldn't do in a REST service, as it's not very "RESTful"
Possible solution 1:
addMessage(textToSend: string) {
let body = JSON.stringify({ textToSend });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post("/api/SendMessage/", body, options);
}
// Server side -1
[HttpPost]
[Route("/api/SendMessage")]
public void SendMessage([FromBody]IDictionary<string, string> msg)
{
var textToSend = msg["textToSend"];
}
// Or create a model and use it
//Server side -2
public class Model
{
public string textToSend { get; set; }
}
public void SendMessage([FromBody]Model model)
Possible solution 2:
addMessage(textToSend: string) {
return this.http.post("/api/SendMessage/" + textToSend);
}
[HttpPost]
[Route("/api/SendMessage/textToSend")]
public void SendMessage(string textToSend)
{
//some code
}
try
addMessage(textToSend: string) {
return this.http.post("/api/SendMessage", msg); //<- Everytime i have some text in textToSend and this is ok
}
changed the name of the variable to match the one you are expecting in the controller

How to retrieve JsonResult data

I have the following Action in my layouts Controller
public JsonResult getlayouts(int lid)
{
List<layouts> L = new List<layouts>();
L = db.LAYOUTS.Where(d => d.seating_plane_id == lid).ToList()
return new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
I am calling this Action from another controller like so:
layoutsController L = new layoutsController();
JsonResult result = L.getlayouts(lid);
My question is: how can I get the data from result object?
Well, have a look how you're building the object:
new JsonResult { Data = L, JsonRequestBehavior = JsonRequestBehavior.AllowGet }
You're setting the L variable to a property called Data. So just read that property:
List<layouts> L = (List<layouts>)result.Data;
There's nothing special about the fact that it's an MVC controller action.
You're simply calling a method which returns an object that was constructed in the method, and reading properties from that object. Just like any other C# code.
I have my class:
public class ResponseJson
{
public string message { get; set; }
public bool success { get; set; }
}
in my method SendEmail
private async Task<JsonResult> SendEmailAsync(ApplicationUser user, string returnUrl, string empleadoNombre, string pwdInic)
i will return my JsonResult
ResponseJson response = new ResponseJson();
response.success = true;
response.message = "OperaciĆ³n exitosa";
return new JsonResult( response);
to read the result returned from my SendEmail method
JsonResult emailSend = await SendEmailAsync(user, returnUrl, empleadoNombre, pwdInic);
ResponseJson response = new ResponseJson();
try
{
string json = JsonConvert.SerializeObject(emailSend.Value);
response = JsonConvert.DeserializeObject<ResponseJson>(json);
}
catch(Exception e)
{
}

Categories