How to call some Controller's method and pass a parameters from a query string - asp.net-mvc-4

in my app I've generated an url like this:
http://www.test.com/?mail=test%40gmail.ba&code=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
The way how I generated Url is posted below:
private string GenerateUrl(string longUrl, string email, string confirmCode)
{
try
{
// By the way this is not working (Home/MailConfirmed) I'm getting message
// Requested URL: /Home/MailConfirmed
// The resource cannot be found.
string url = longUrl + "/Home/MailConfirmed";
var uriBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["mail"] = email;
query["code"] = confirmCode;
uriBuilder.Query = query.ToString();
uriBuilder.Port = -1;
url = uriBuilder.ToString();
return url;
}
catch (Exception ex)
{
return "Error happened: " + ex.Message;
}
}
In longUrl I'm passing www.test.com, in email I'm passing
test#gmail.com and so on..
There are informations about my website:
www.test.com
mail:test#gmail.com
confirmcode:71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
And in my HomeController.cs there is a method which should took parameters out of query string - url and pass it to the method which should activate users account by getting user by mail (mail is unique) and comparing this guid with guid in database. So I'm wondering how can I call this method?
So my method looks like this:
public JsonResult MailConfirmed(string mail, string confirmCode)
{
try
{
// Here I will get user and update it in DB
return Json("success", JsonRequestBehavior.AllowGet);
}
catch(Exception ex)
{
return Json("fail", JsonRequestBehavior.AllowGet);
}
}
So my question is how is possiblee for user to click on following link and to get an my method invoked.. ?
Thanks a lot
Cheers

In order to navigate to your MailConfirmed(), your url would need to be
http://www.test.com/Home/MailConfirmed?mail=test%40gmail.ba&confirmcode=71147ff9-87ae-41fc-b53f-5ecb3dbe5a01
Note the segments for the controller and action names, and code=xxx should be confirmcode=xxx to match the name of the parameter in the method.
You can simplify your code (and delete your GenerateUrl() method) by making use of UrlHelper methods to generate the url).
To generate the above url, all you need in your controller method is
string url = Url.Action("MailConfirmed", "Home",
new { mail = email, confirmcode = confirmCode },
this.Request.Url.Scheme);

Related

How to find api action path from another action

In My Reserve ApiController, I need to have may BankRedirect action's path in a string and Url.Route has been used but it doesn't work.
public string GoToBank(string token, string username )
{
string path Url.Route("BankRedirect", new { controller = "Reserve"} , new { userId = "" }))
return path;
}
[Route("BankRedirect")]
[HttpPost]
[BasicAuthenticationFilter]
public async Task<UpdateResult<string>> BankRedirect( [FromBody]string userId)
{
}
The corresponded path for decorating action with [Route("BankRedirect")] is /BankRedirectץ
The given Url.Route output is Reserve/BankRedirect.
/BankRedirect != Reserve/BankRedirect
You should change one of them, either:
[Route("Reserve/BankRedirect")]
Or
return "BankRedirect";

How to request same parameter twice in query string?

I am trying to request the following query string url: api/item?name=storm&name=prest
I am using the following code below and I cannot get the code to work.
public class ItemController : ApiController
{
private cdwEntities db = new cdwEntities();
public HttpResponseMessage Get([FromUri] Query query)
{
var data = db.database_ICs.AsQueryable();
if (query.name != null)
{
**data = data.Where(c => c.Name.Split("&").Contains(query.name));**
}
if (query.id!= null)
{
data = data.Where(c => c.ID== query.id);
}
if (!data.Any())
{
var message = string.Format("No data was found");
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, data);
}
}
Any help would be very much appreciated.
You can use post Api and send array of [name].
name = [item1,item2....]
public void Post([FromBody] List<string> name) {
}
You can not pass same name key in Querystring. Browser/Code did not identified which is correct value, if you want multiple value then pass as a object.

ActionMailer.net mvc4 simple webapp email sender

namespace ActionMailSample.Controllers
{
public class MailController : MailerBase
{
//
// GET: /Mail/
public EmailResult SampleEmail()
{
From = "ExampleEmail#this.com";
To.Add("ExampleEmail#there.com");
Subject = "tha pikseis kolopsaro";
return Email();<---ERROR no overload for method Email takes 0 arguments.
}
}
}
You must enter the same name of the EmailResult and the viewmodel that came from the view where is the form to send.
public class MailController : MailerBase
{
public EmailResult SampleEmail(mail_ViewModel model)
{
To.Add("destination#email.com");
From = "from#email.com";
Subject = "Subject of Email";
return Email("SampleEmail", model);
}
}
Dont forget when you create the view, append .txt or .html to Plain or Html email.
The name of this view in plain text will be SampleEmail.txt that will become the filename SampleEmail.txt.cshtml
In the view (SampleEmail.txt.cshtml) you can put something like this:
#model TEST.Models.mail_ViewModel
#{
Layout = null;
}
Contact from Website
Name: #Html.Raw(Model.Nome)
Email: #Html.Raw(Model.Email)
Subject: #Html.Raw(Model.Subject)
Message: #Html.Raw(Model.Message)
Hope this helped.
The method Email() expects one or more parameters. Consult the documentation for the Email() function to see what is expected and supply this information.

Struts2 more than one action in one class

I'm using Struts2. I have two web forms that have the same code. I would like to eliminate one form. Here is the structure of my Struts project.
\Web Pages
form.jsp
\WEB-INF
\Content
error.jsp
form.jsp
success.jsp
\Source Packages
\action
MyAction.java
MyAction.java
package action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.*;
public class MyAction extends ActionSupport {
#Action(value = "foo", results = {
#Result(name = "input", location = "form.jsp"),
#Result(name = "success", location = "success.jsp"),
#Result(name = "error", location = "error.jsp")
})
public String execute() throws Exception {
if (user.length() == 1) {
return "success";
} else {
return "error";
}
}
private String user = "";
public void validate() {
if (user.length() == 0) {
addFieldError("user", getText("user required"));
}
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
}
I tried to eliminate form.jsp under \Web Pages by adding a new action method to MyAction.java.
#Action(value="bar", results = {
#Result(name = "success", location = "form.jsp"),
})
public String another() {
return "success";
}
But I got the following error when I go to http : //localhost .../bar.action
HTTP Status 404 - No result defined for action action.MyAction and result input
Your MyAction has an implementation of validate(), which means it is validation aware.
What's happening is that you're calling another, but validate() is kicking in (as it's in the interceptor stack). Validation is failing, and therefore sending to INPUT result, which is not defined in another.
You should
Add #SkipValidation to the another method if you don't want validation there
Add the INPUT result to another() if you want a default input result
On a more general note, when you get that kind of error (No result defined for action X and result input) it usually means you're either having validation errors, parameter population errors (eg: an exception in preparable).

Find Matching OperationContract Based on URI

...or "How to determine which WCF method will be called based on URI?"
In a WCF service, suppose a method is invoked and I have the URI that was used to invoke it. How can I get information about the WCF end point, method, parameters, etc. that the URI maps to?
[OperationContract]
[WebGet(UriTemplate = "/People/{id}")]
public Person GetPersonByID(int id)
{
//...
}
For instance, if the URI is: GET http://localhost/Contacts.svc/People/1, I want to get this information: service name (Service), Method (GetPersonByID), Parameters (PersonID=1). The point is to be able to listen for the request and then extract the details of the request in order to track the API call.
The service is hosted via http. This information is required before the .Net caching can kick in so each call (whether cached or not) can be tracked. This probably means doing this inside HttpApplication.BeginRequest.
FYI I'm hoping to not use reflection. I'd like to make use of the same methods WCF uses to determine this. E.g. MagicEndPointFinder.Resolve(uri)
Here is what I ended up doing, still interested if there is a cleaner way!
REST
private static class OperationContractResolver
{
private static readonly Dictionary<string, MethodInfo> RegularExpressionsByMethod = null;
static OperationContractResolver()
{
OperationContractResolver.RegularExpressionsByMethod = new Dictionary<string, MethodInfo>();
foreach (MethodInfo method in typeof(IREST).GetMethods())
{
WebGetAttribute attribute = (WebGetAttribute)method.GetCustomAttributes(typeof(WebGetAttribute), false).FirstOrDefault();
if (attribute != null)
{
string regex = attribute.UriTemplate;
//Escape question marks. Looks strange but replaces a literal "?" with "\?".
regex = Regex.Replace(regex, #"\?", #"\?");
//Replace all parameters.
regex = Regex.Replace(regex, #"\{[^/$\?]+?}", #"[^/$\?]+?");
//Add it to the dictionary.
OperationContractResolver.RegularExpressionsByMethod.Add(regex, method);
}
}
}
public static string ExtractApiCallInfo(string relativeUri)
{
foreach (string regex in OperationContractResolver.RegularExpressionsByMethod.Keys)
if (Regex.IsMatch(relativeUri, regex, RegexOptions.IgnoreCase))
return OperationContractResolver.RegularExpressionsByMethod[regex].Name;
return null;
}
}
SOAP
private static void TrackSoapApiCallInfo(HttpContext context)
{
string filePath = Path.GetTempFileName();
string title = null;
//Save the request content. (Unfortunately it can't be written to a stream directly.)
context.Request.SaveAs(filePath, false);
//If the title can't be extracted then it's not an API method call, ignore it.
try
{
//Read the name of the first element within the SOAP body.
using (XmlReader reader = XmlReader.Create(filePath))
{
if (!reader.EOF)
{
XmlNamespaceManager nsManager = new XmlNamespaceManager(reader.NameTable);
XDocument document = XDocument.Load(reader);
//Need to add the SOAP Envelope namespace to the name table.
nsManager.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
title = document.XPathSelectElement("s:Envelope/s:Body", nsManager).Elements().First().Name.LocalName;
}
}
//Delete the temporary file.
File.Delete(filePath);
}
catch { }
//Track the page view.
}