Web API Get Method with Complex Object as Paramete

2020-03-21 10:25发布

问题:

How to send a Complex Object( Which may have huge data) to a Web API Get Method? I know I can user 'FromUri' option, but since the data is too large I can't use that option. I want to user 'FromBody' option. But can I post data to a Get Method?????

Please guide me here...thanks in advance

回答1:

How to send a Complex Object( Which may have huge data) to a Web API Get Method?

You can't. GET methods do not have request body. You have to send everything in the query string which has limitations.

You should use POST instead.



回答2:

You need to create a method similar to the below:

[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") };
}

If your POSTing data larger than 4MB, then you'll need to adjust your web.config to configure IIS to accept more, the below example sets the maxRequestLength and maxAllowedContentLength to 10MB:

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

and

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


回答3:

use OData maybe its fine for not too big objects

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

Or use FromUri like below

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