简体   繁体   中英

RestFul action methods in ASP.NET MVC 3

I am unable to retrieve my POST request body inside my action method .

I use fiddler to initiate a post request .

Here is the controller I am using .

public class EventController : Controller
{
    //
    // GET: /Event/

    public ActionResult Index()
    {
        return View();
    }


    [HttpPost]
    [ActionName("Event")]
    public String AddSurvey()
    {
        // ... logic to modify or create data item

        return "Ahmed" + Request["person"];
    }
}

This is how my global.asax is configured

 public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");


        routes.MapRoute(null, "Event",
             new { controller = "Event", action = "Event" });

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/{id}", // URL with parameters
            new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
        );



    }

When i intiate the POST request from fiddler , my breakpoint on the method invokes . However when i watch the value for Request["person"] , there is null in it .

Is it the routes defined in the global.asax ? Please help

Try to rename the Index action to Event . [ActionName("Event")] indicates that your Get action is called Event .

When someone looks for RESTful methods in the regular ASP.NET MVC, Its important for me to make sure he is aware of WebAPI , which exactly fit this need .

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

I dont konw , how . or why . but this worked

  [HttpPost]
    [ActionName("Event")]
    public String AddSurvey()
    {
        // ... logic to modify or create data item
        string body;
        using (StreamReader reader = new StreamReader(Request.InputStream))
        {
            body = reader.ReadToEnd();
            reader.Close();
        }


        return body;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM