在ASP.NET MVC 4中发布请求转到WEB API中的Get函数

时间:2014-12-17 13:20:53

标签: c# asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api

我在ASP.NET Web API中创建了一个控制器。以下是控制器的代码

public class CalculateController : ApiController
{
    public IEnumerable<string> Get()
    {

        return new string[] { "from get method" };

    }

    public IEnumerable<string> Post([FromBody]string value)
    {

        return new string[] { "from post method" };
    }
}

以下是我用来向webAPI发布帖子请求的代码

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://localhost:62479/api/calculate");

        StringBuilder postdata = new StringBuilder("value=Anshuman");
        byte[] data = Encoding.UTF8.GetBytes(postdata.ToString());
        httpWReq.Method = "POST";
        httpWReq.ContentType = "application/x-www-form-urlencoded";
        httpWReq.ContentLength = data.Length;

        using (Stream stream = httpWReq.GetRequestStream())
        {
            stream.Write(data, 0, data.Length);
        }
        HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
        string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

问题是,即使我发出 POST 请求,数据也会从Controller的 GET 方法返回。我没有对Web API项目的默认配置进行任何更改。我正在使用MVC 4.

感谢您的时间。如果需要任何其他信息,请添加评论。

我在同一台机器上运行Visual Studio 2012中的两个项目。

2 个答案:

答案 0 :(得分:3)

没有参数的帖子方法。

默认情况下如下:

public void Post([FromBody]string value)
{
    //do something with data you posted
}

在你的情况下,如果你想要返回一些字符串数据:

public IEnumerable<string> Post([FromBody]string value)
{
    return new string[] { "from post method" };
}

刚刚测试过您的代码。它工作正常,post方法正确命中。但就我而言,我在WebApiCOnfig.cs中得到了这个。它有助于使web api路由更加灵活。

        config.Routes.MapHttpRoute(
            name: "DefaultApiWithId",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"\d+" }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApiWithAction",
            routeTemplate: "api/{controller}/{action}"
        );

        config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
        config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
        config.Routes.MapHttpRoute("DefaultApiPut", "api/{controller}", new { action = "Put" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Put) });
        config.Routes.MapHttpRoute("DefaultApiDelete", "api/{controller}", new { action = "Delete" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Delete) });

答案 1 :(得分:0)

您可以将HttpPost和HttpGet操作属性添加到相关操作中,这些操作将限制帖子被路由引导到获取操作