3

http://documentation.mailgun.net/quickstart.html contains some example code for a http handler in Django:

    # Handler for HTTP POST to http://myhost.com/messages for the route defined above
    def on_incoming_message(request):
    if request.method == 'POST':
     sender    = request.POST.get('sender')
     recipient = request.POST.get('recipient')
     subject   = request.POST.get('subject', '')

     body_plain = request.POST.get('body-plain', '')
     body_without_quotes = request.POST.get('stripped-text', '')
     # note: other MIME headers are also posted here...

     # attachments:
     for key in request.FILES:
         file = request.FILES[key]
         # do something with the file

 # Returned text is ignored but HTTP status code matters:
 # Mailgun wants to see 2xx, otherwise it will make another attempt in 5 minutes
 return HttpResponse('OK')

What is the equivalent in ASP.NET C#?

I have tried Request.Form["sender"] for example, but the Mailgun log records a HTTP 500 error code.

Thanks for your help.

Lewis Buckley
  • 1,583
  • 15
  • 22
  • Have you checked all your request.form collection to see if anything is returned? – PMC Dec 12 '11 at 21:54
  • @PaulMcCowat Thanks for your quick comment. To be honest, I'm also having difficulty debugging this, because it's the Mailgun web service and needs to post to a website, I keep having to try something new and then upload it each time. I'm trying to store the posted data to a database. But just keep getting the 500 Internal Server Error. – Lewis Buckley Dec 12 '11 at 22:07
  • We need to know what the server error actually is. – Andrew Barber Dec 12 '11 at 22:27
  • Well I have set the page up to be very simple: if I use my web browser to visit the page it simply inserts two values into the database table and works fine. It's only when the web service tries to post that there is a problem. I have set EnableEventValidation on the page to false, to no effect. I don't know how to go about finding what the error is unfortunately. – Lewis Buckley Dec 12 '11 at 22:50
  • OK. I have used a HTTP tool, Fiddler to post data to my form. It works only when Content-Length: 0 is set. Otherwise there is an error. iIthink this is because IIS requires Content-Length to be set. Is there a way to disable this requirement? – Lewis Buckley Dec 12 '11 at 23:01
  • I needed to set ValidateRequest to false in the page directive. Thanks. – Lewis Buckley Dec 13 '11 at 00:00
  • I have also discovered that ASP.NET errors are logged in the Windows Event Log in the Application log. This is very useful for debugging this kind of problem. – Lewis Buckley Dec 13 '11 at 12:18

3 Answers3

5

Main I wish i would have found this about 6 hours ago ...

Here is what you need to do if you are using mvc and the razor view engine

    [HttpPost]
    [ValidateInput(false)]
    public ActionResult GoTruckGo(FormCollection oColl)
    {
        try
        {
             string sender = Request.Unvalidated().Form["sender"];
             string body =   Request.Unvalidated().Form["body-plain"];
             sendLog(body);
             // do something with data 
         }
        catch (Exception ex)
        {
            sendLog("entered catch = "+ ex.Message);
        }

        return Content("ok");

    }
z3nd3v
  • 131
  • 2
  • 3
4

I needed to set ValidateRequest to false in the page directive.

Sample Code-

sms.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="sms.aspx.cs" EnableEventValidation="false" ValidateRequest="false" Inherits="sms" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server">
    <p>SMS</p>
</form>
</body>
</html>

sms.aspx.cs

public partial class sms : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
    string subject = Request.Params["subject"];
    string message = Request.Params["body-plain"];

    using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["YOURCONNECTIONSTRING"].ConnectionString))
    {
        cn.Open();

        using (SqlCommand cm = cn.CreateCommand())
        {
            cm.CommandType = CommandType.Text;
            cm.CommandText = "INSERT INTO SMS (subject, message, DateTime) VALUES (@Subject, @Message, @Dateandtime);";
            cm.Parameters.Add("@Subject", SqlDbType.NVarChar).Value = subject;
            cm.Parameters.Add("@Message", SqlDbType.NVarChar).Value = message;
            cm.Parameters.Add("@Dateandtime", SqlDbType.DateTime).Value = DateTime.Now.ToString();

            SqlDataReader dr = cm.ExecuteReader();
            dr.Dispose();
            cm.Dispose();

        }

    }

}
}

Hope this helps someone else using Mailgun and C#.

Talljoe
  • 14,593
  • 4
  • 43
  • 39
Lewis Buckley
  • 1,583
  • 15
  • 22
  • Is this the same page that also calls your MailGun send routines? I'm trying to understand how to tell MailGun where to send responses to **smtpClient1.Send(mailMessage1)** I send out. When a message fails, I want to get why. Next, I need to learn what to do about failures. –  Sep 15 '16 at 15:58
2

My VB.Net Version

' Get form data? 
Dim message As String = String.Empty
Dim mailgun As NameValueCollection = Request.Form
Dim key As String
Dim values() As String
For Each key In mailgun.Keys
    values = mailgun.GetValues(key)
    For Each value As String In values
        ' create a new string
        message &= key & "-" & value & "|"
        ' MsgBox(key & " - " & value)
    Next value
Next key
' save message
ransems
  • 641
  • 7
  • 19