将长 HTML 字符串作为参数从 MVC 控制器传递给 Web API
Pass long HTML string as parameter to Web API from MVC Controller
我正在开发 Web API 以及 MVC 应用程序。现在我的要求是将 HTML 作为字符串从 MVC 控制器传递给 Web API 方法。
我在我的 MVC 应用程序中使用了以下代码来调用网络服务:
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
}
}
下面是我的方法在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);
}
}
但是上面的代码不起作用,我得到一个错误
然后我实现了日志记录,发现 Web API 中的参数 htmlString 是空的,这不应该发生,因为我正在传递我的 HTML
我什至尝试在 MVC 中编码 HTML,然后将其传递给 Web API,但这也不起作用。
遇到这种情况我该怎么办?
[已编辑]
我试图从 MVC 应用程序传递如下所示的简单 HTML,我在 Web API
中获得了值
<html>
<body>
Hello World.
</body>
</html>
但是它不适用于我的长HTML
我认为您需要增加允许的 URL 长度或查询字符串大小:
<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.
参考:
好吧,我认为最好的方法是,如果你想传递一些东西到网络api,你应该使用POST 请求 在 http 请求正文中发送 HTML,因此您无需担心内容大小。
我正在开发 Web API 以及 MVC 应用程序。现在我的要求是将 HTML 作为字符串从 MVC 控制器传递给 Web API 方法。
我在我的 MVC 应用程序中使用了以下代码来调用网络服务:
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
}
}
下面是我的方法在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);
}
}
但是上面的代码不起作用,我得到一个错误
然后我实现了日志记录,发现 Web API 中的参数 htmlString 是空的,这不应该发生,因为我正在传递我的 HTML
我什至尝试在 MVC 中编码 HTML,然后将其传递给 Web API,但这也不起作用。
遇到这种情况我该怎么办?
[已编辑] 我试图从 MVC 应用程序传递如下所示的简单 HTML,我在 Web API
中获得了值<html>
<body>
Hello World.
</body>
</html>
但是它不适用于我的长HTML
我认为您需要增加允许的 URL 长度或查询字符串大小:
<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.
参考:
好吧,我认为最好的方法是,如果你想传递一些东西到网络api,你应该使用POST 请求 在 http 请求正文中发送 HTML,因此您无需担心内容大小。