Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-web-api2

Pass long HTML string as parameter to Web API from MVC Controller


I am working on development of Web API as well as MVC application. Now my requirement is to pass HTML as a string from MVC controller to Web API method.

I have used the below code in my MVC application to call web service:

 using (var client = new HttpClient())
        {
            byte[] Result = null;

            client.BaseAddress = new Uri("http://localhost:1004/");

            HttpResponseMessage Res = await client.GetAsync(string.Format("api/Method?htmlString={0}", htmlString));

            if (Res.IsSuccessStatusCode)
            {
                Result = Res.Content.ReadAsByteArrayAsync().Result;
            }

            if (Result != null)
            {
                //Work with byte array
            }
        }

Below is the declaration of my method in Web API

[HttpGet]
    [Route("api/Method")]
    public HttpResponseMessage Method(string htmlString)
    {
       try
       {
         //work with htmlString
        }
        catch (Exception ex)
        {
            HttpError err = new HttpError(ex.ToString());
            return Request.CreateResponse(HttpStatusCode.NotFound, err);   
        }
    }

But the above code does not work and I am geting an error

Then I have implemented logging and found that the parameter htmlString in Web API is empty, which should not happen as I am passing my HTML

I have even tried to Encode HTML in MVC and then pass it to Web API, but that is also not working.

What can I do in this case?

[Edited] I have tried to pass simple HTML which is shown as below from MVC application and I got the value in Web API

<html>
<body>
    Hello World.
</body>
</html>

However it is not working with my long HTML


Solution

  • I think you need to increase the allowed URL length or query string size:

    <httpRuntime maxUrlLength="260" maxQueryStringLength="2048" />
    

    To allow longer or shorter paths (the portion of the URL that does not include protocol, server name, and query string), modify the maxUrlLength attribute. To allow longer or shorter query strings, modify the value of the maxQueryStringLength attribute.

    Reference:

    Expanding the Range of Allowable URLs