我有一个ASP.NET MVC剃须刀C#应用程序,它具有1个控制器和1个接受参数的POST函数.然后该函数返回HttpResponseMessage.
public class VersionController : Controller
{
[HttpPost]
public HttpResponseMessage LatestClientVersion(string myVar)
{
string outputMessage = "This is my output";
...
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(outputMessage, Encoding.UTF8, "text/plain");
return resp;
}
}
为了进行测试,我使用Postman对URL进行POST请求.
它响应:
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}
我的状态码响应良好,但是我看不到字符串“这是我的输出”
因此,我认为这可能与C#特定的东西有关,因此我制作了一个C#winforms应用程序进行测试.因此,当我单击按钮时,它将执行以下操作:
public void TestWebRequest()
{
try
{
WebRequest request = WebRequest.Create(txtURL.Text);
request.Method = "POST";
string postData = "myVar=test";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
HttpWebResponse httpResponse = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Send text to the textbox
SetOutputText(responseFromServer);
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
SetOutputText(ex.Message);
}
}
}
此功能可以完美运行,但我仍然得到与邮递员中相同的响应…
如何获得实际的内容“这是我的输出”?
编辑
我提出了另一个简单的HttpGet请求
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using System.Net.Http.Headers;
using System.Net;
using System.Text;
namespace MyWebService.Controllers
{
public class VersionController : Controller
{
[HttpGet]
public HttpResponseMessage Test()
{
HttpResponseMessage response = new HttpResponseMessage();
response.Content = new StringContent("This is my output");
return response;
}
}
}
使用邮递员时,我得到以下结果
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.StringContent, Headers:
{
Content-Type: text/plain; charset=utf-8
}
解决方法:
您正在混合使用WebAPI和MVC.
对于WebAPI,HttpResponseMessage(具有Content = new StringContent(“ the string”))将起作用.
对于MVC,为syntax to return a string is(请注意ActionResult返回类型和Content()调用):
public ActionResult Test()
{
return Content("This is my output");
}