简体   繁体   中英

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.

So can anyone tell me what should I do in this case?

Thanks in advance

[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

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

好吧,我认为最好的办法是,如果您尝试某些内容传递给Web api,则应该使用POST请求在HTTP请求正文中发送HTML,因此您不必担心内容大小。

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