Richard S.
Richard S.

Reputation: 743

Passing values from controller to WebAPI

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:

Upvotes: 1

Views: 2398

Answers (1)

Kim
Kim

Reputation: 1814

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)

Upvotes: 2

Related Questions