Routing POST with Query Parameters in MVC Web API - c#

In a Web Apì project, I would like to use something like:
POST/mycontroller/1
but also POST/mycontroller/1?user=john
It is easy with GET because the framework routes correctly to each function. However, when I use POST, it does not work. I have 2 POST functions in the same controller. For example:
void Post(int id, string content)
and
void Post(int id, string content, string user)
I would hope when I call POST/mycontroller/1?user=john, the framework routes to Post(int id, string content, string user)
I know that I can use binding models, doing a model class and one unique POST function, but it is a mess because I have many functions and I would like to be able to use the query parameters to route the correct function.
Is it possible?

Try declaring parameter with [FromBody] and [FromUri] attribute like this:
public string Post(int id, [FromBody]string content, [FromUri] string user)
{
return "content = " + content + "user = " + user;
}
With above code I was able to call
/Test/1?user=Ryan
Request body
"Test Body"
and the result is:
"content = Test Bodyuser = Ryan"
Hope this helps.

Related

Swift Posting to .net core with Post Method Not Working, Getting not Authorized Back From response

I'm completely stuck. I've tried everything. I was given this code snippet for .net i believe:
[HttpGet, HttpPost]
public async Task<ActionResult<string>> getInfo(string number, string authToken, string profileName)
and I've been trying to get a post request with it to work. GET works fine, however I have a call where i need to upload an iFile form and I figure if I get the post call working with the other methods parameters I should be able to get this.
I tried:
let params = ["number": number, "authToken" : authToken, "profileName" : profileName]
var request = URLRequest(url: URL(string: fullURL)!)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField:"Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try? JSONEncoder().encode(params)
let task = URLSession.shared.dataTask(with:request) {//...}
What Can I Do To Make this Work? Am I missing information? Because I need to be able to POST to this:
[Route("uploadImage")]
[HttpGet, HttpPost]
public async Task<ActionResult<string>> uploadImage(List<IFormFile> files, string authToken, string number, string profileName, int profileNum, string ID)

How to form a URL to access the webapi controller?

I would like to know how we will create a Route URL to access the above function. Error message comes stating that I cannot access the controller
[HttpGet]
[Route("api/TeacherData/ListTeachers/{SearchKey?}&{order?}")]
public List<Teacher> ListTeachers(string SearchKey = null, string order = null)
{
}
I know it's your API and your design, but following the REST API patterns we should stick to simple API URLs, something like api/teachers could be easier to understand by the consumers if they know that the endpoint uses the GET method.
About your actual question, you could change the code to use [FromQuery] to expect parameters that should come from the query string:
[HttpGet]
[Route("api/teachers")]
public List<Teacher> ListTeachers([FromQuery] string searchKey = null, [FromQuery] string order = null)
{
}
Then, from the consumer side, you could trigger this endpoint using the following URL:
GET http://myapi.com/api/teachers?searchKey=keyValue&order=orderValue
If you keep your URL structure it should something like this:
GET http://myapi.com/api/TeacherData/ListTeachers?searchKey=keyValue&order=orderValue

Web Api c# Get Query Sring from url - Asp.net

I got a url where it's method is post but I want to pass some paramets by get method, I am using c# MVC asp.net
as the follow link
http://site/api/user/seach/?value=here&value2=here2
I am trying to get this using
public IHttpActionResult Get()
{
var queryString = this.Request.GetQueryNameValuePairs();
}
And I already tried to use
string p = Request.QueryString["value"];
But it seems to work only in controller base exteds
Is there some way to get this value get in a post method ?
Sounds like you'd like to use the POST verb but send data through querystring, in that case you can:
public IHttpActionResult Post([FromUri]string value)
{
// do whatever you need to do here
}

MVC 3 NopCommerce '$' character as part of the name of an url parameter

I am working with NopCommerce by implementing the payment by credit card.I'm not using plugin but a simple redirect to the page of payment.Payment done then I get redirected to the page\view (http://localhost/Nop240/CreditCardPayment/Result) where I analyze the resultof the transaction reading the url parameters.
In the RouteProvider.cs class i have mapped the return url like this:
routes.MapLocalizedRoute("CreditCardPaymentResult", "CreditCardPayment/Result/s/{session_id}/s/{codAut}/s/{alias}/s/{orario}/s/{data}/s/{mac}/s/{importo}/s/{cognome}/s/{nazionalita}/s/{pan}/s/{divisa}/s/{email}/s/{scadenza_pan}/s/{esito}/s/{codTrans}/s/{nome}/s/{messaggio}/s/{tipo_servizio}/s/{$BRAND}/", new { controller = "Checkout", action = "CreditCardPaymentResult" }, new[] { "Nop.Web.Controllers" });
In the controller i have writen this code
public ActionResult CreditCardPaymentResult(string session_id, string codAut, string alias, string orario, string data, string mac, string importo, string BRAND, string cognome, string nazionalita, string pan, string divisa, string email, string scadenza_pan,string esito, string codTrans, string nome, string messaggio, string tipo_servizio)
The return url is something like this
http://localhost/Nop240/CreditCardPayment/Result?session_id=w5pl05e3s2f1ki5bdg30xymy&codAut=TESTOK&alias=payment_testm_urlmac&orario=142525&data=20121008&mac=c62373ff789d451bcda0bb84d1d679114107aecd&importo=1&$BRAND=MasterCard&cognome=wwww&nazionalita=ITA&pan=525599XXXXXX9992&divisa=EUR&email=fabrizio%40xxx.net&scadenza_pan=201402&esito=OK&codTrans=0000000000000162&nome=wwww&messaggio=Message+OK&tipo_servizio=null
the problem is how intercept $BRAND url parameter.
Can help me please?
have a look at url encoding here https://www.tutorialspoint.com/html/html_url_encoding.htm
you need to encode the dollar sign.

in asp.net-mvc controller, what is the best way to generate a URL

right now i take the
RequestContext
and pass this into a UrlHelper like this:
UrlHelper u = new UrlHelper(context);
string hrSyncUrl = u.Action("Update", "Person");
but the issue is that this seems to return:
/Person/Update
instead of:
http://www.mysite.com/Person/Update
so, given a controller and and action name, how can i generate a FULL url from inside a controller?
the reason that i need this is that i am generating an email so i need the full url to put in the body of that email.
By using the proper overload:
string hrSyncUrl = u.Action("Update", "Person", null, "http");
And to avoid hardcoding the protocol you could fetch it from the request:
var protocol = context.HttpContext.Request.Url.Scheme;
string hrSyncUrl = u.Action("Update", "Person", null, protocol);
see ASP.NET MVC create absolute url from c# code

Categories