Web API获取复杂对象作为参数的方法

时间:2013-09-27 11:47:32

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

如何将复杂对象(可能包含大量数据)发送到Web API获取方法? 我知道我可以使用'FromUri'选项,但由于数据太大,我无法使用该选项。我想用'FromBody'选项。但是我可以将数据发布到Get Method ?????

请在这里指导我......提前致谢

3 个答案:

答案 0 :(得分:16)

  

如何将复杂对象(可能包含大量数据)发送到Web API获取方法?

你做不到。 GET方法没有请求体。您必须在查询字符串中发送有限制的所有内容。

您应该使用POST。

答案 1 :(得分:1)

您需要创建一个类似于以下的方法:

[HttpPost]
public HttpResponseMessage MyMethod([FromBody] MyComplexObject body)
{
    try
    {
        // Do stuff with 'body'
        myService.Process(body);
    }
    catch (MyCustomException)
    {
        return new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("FAILED") };
    }

    return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("OK") };
}

如果您的POSTing数据大于4MB,那么您需要调整web.config以将IIS配置为接受更多,下面的示例将maxRequestLength和maxAllowedContentLength设置为10MB:

<system.web>
    <httpRuntime maxRequestLength="10240" />
</system.web>

<system.webServer> 
      <security> 
          <requestFiltering> 
             <requestLimits maxAllowedContentLength="10485760" /> 
          </requestFiltering> 
      </security> 
</system.webServer>

答案 2 :(得分:0)

使用OData可能对于不太大的对象很好

https://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api

或使用FromUri,如下所示

public MethodName Get([FromUri] Model model,int page,int pageSize)

相关问题