I have a need to track emails and pages on our website. We want to use a WebAPI for this, however I am very new and the examples I found were hard to follow. Here is my problem:
I have an EmailTrackerContoller with code like below:
public class EmailTrackingController : Controller
{
[OutputCache(NoStore = true , Duration = 0)]
[HttpPost]
public ActionResult GetPixel(string email, Guid emailID) {
var client = new HttpClient();
var endpoint = "http://localhost:2640/api/EmailTracker/SaveEmail"; --path to my API
var response = await client.PostAsync(endpoint, null); --this does not work
const string clearGif1X1 = "R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==";
return new FileContentResult(Convert.FromBase64String(clearGif1X1) , "image/gif");
}
}
I have also created a WebAPI that has a HttpPost Method Called SaveEmail:
[HttpPost]
public HttpResponseMessage SaveEmail([FromBody]string value) { --How do I get the Email and Guid I need from here?
var a = new DL.EmailTracking();
a.Insert("<email>" , Guid.NewGuid());
return Request.CreateResponse(HttpStatusCode.Accepted , "");
}
Couple of questions on this:
- How do you pass values from the controller to the WebApi?
- Any easy to follow examples would be great, of if you have a link that would be useful as well.
-
2What do you means by passing data from controller to the webApi? Controller is the entry point of your API to your app logicacostela– acostela2017年07月28日 12:27:33 +00:00Commented Jul 28, 2017 at 12:27
-
I'm a little confused. There are controller WebAPI's, so you send values from the view to the controller WebAPIGrizzly– Grizzly2017年07月28日 12:27:37 +00:00Commented Jul 28, 2017 at 12:27
-
I have a website that needs to call this webapi from a controller. The webApi has a controller as well I am trying to pass values form the website to the webapi so that I can preform a database insert. I just don't know how to properly call the webapi passing in the email and id, and how to retrive it on the webapi side. Does that make sense, sorry, still kinda new to MVC and Webapi'sRichard S.– Richard S.2017年07月28日 12:31:17 +00:00Commented Jul 28, 2017 at 12:31
-
This will help you to make request to from C# stackoverflow.com/questions/19448690/…Bharat– Bharat2017年07月28日 12:33:24 +00:00Commented Jul 28, 2017 at 12:33
-
Why do you need a web api?Shahzad– Shahzad2017年07月28日 12:36:35 +00:00Commented Jul 28, 2017 at 12:36
1 Answer 1
The second parameter of PostAsync
is the content of the call.
Serialize the object as JSON that contains the values you want and add it as the content.
var obj = new { Email = "[email protected]" };
HttpStringContent msg = new HttpStringContent(JsonConvert.SerializeObject(obj));
var response = await client.PostAsync(endpoint, msg);
Modify the receiving method to receive the desired properties. I'd use a class as the methods parameter but you can use [FromBody]
with all the properties listed as well.
public HttpResponseMessage SaveEmail(EmailSave model)