我在MVC控制器中有以下代码,它将示例guid字符串放入HttpResponseMessage中:
public class CertifyController : Controller
{
[HttpPost]
public async Task<HttpResponseMessage> NewCertifyOfferRequestAsync(string requestString)
{
string activityId = "30dd879c-ee2f-11db-8314-0800200c9a66";
HttpResponseMessage httpResponseMessage = new HttpResponseMessage();
httpResponseMessage.Content = new StringContent(activityId);
return httpResponseMessage;
}
}
我使用以下代码通过控制台应用程序调用此Controller:
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:84928/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string requestString = "df5f5587-f1ef-449a-9d20-7f386ea638a8";
HttpResponseMessage response = await client.PostAsJsonAsync("Certify/NewCertifyOfferRequestAsync", requestString);
if (response.IsSuccessStatusCode)
{
string activityId = await response.Content.ReadAsStringAsync();
Console.WriteLine("Received activity id: " + activityId);
}
}
我希望在回复中收到activityId“30dd879c-ee2f-11db-8314-0800200c9a66”。但相反,activityId获得“StatusCode:200,ReasonPhrase:'OK',版本:1.1,内容:System.Net.Http.StringContent,标题:\ r \ n {\ r \ n内容类型:text / plain; charset来自ReadAsStringAsync调用的“utf-8 \ r \ n}”。
我应该如何更改activityId的赋值,以便它在Controller中生成activityId?
答案 0 :(得分:3)
如果是webapi,您应该能够更改方法签名以返回&#34;字符串&#34;而不是HttpResponseMessage。
e.g
public string Get(int id)
{
return "value";
}
对于详细示例,您可以使用visual studio创建WebApi Web应用程序,并查看&#34; ValuesController.cs&#34;