这让我有点头疼。最终,我试图返回一个图像,但我一直在尝试并将其简化为使用字符串。
我想要什么:转到网址:
http://xxx/api/helloworld/1
回应:“你好,世界!”
以下 web api 声明适用于提供的 url;
public string Get([FromUri]int id) { return "Hello World"; }
public Task<string> Get([FromUri]int id) { return "Hello World"; }
什么不起作用;
public HttpResponseMessage Get([FromUri]int id)
{
return Request.CreateResponse<string>(HttpStatusCode.OK, "Hello World");
}
public HttpResponseMessage Get([FromUri]int id)
{
HttpResponseMessage response = new HttpResponseMessage();
string text = "Hello World";
MemoryStream test = new MemoryStream();
test.Write(ConversionUtilities.ToBytes(text) /*custom string->byte[] method, UTF-8 encoding*/, 0, text.Length);
response.Content = new StreamContent(test);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
response.StatusCode = HttpStatusCode.OK;
return response;
}
当我有一个返回类型为 HttpResponseMessage 的 Get() 时会发生什么是返回以下错误;
No HTTP resource was found that matches the request URI "http://xxx/api/helloworld/1"
此错误仅针对此特定返回类型出现。现在,我在 WebApiConfig.cs 文件中的路由如下(适用于“字符串”返回类型);
// Controller with ID
// To handle routes like "/api/VTRouting/1"
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: "api/{controller}/{id}",
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
// Controllers with Actions
// To handle routes like "/api/VTRouting/route"
config.Routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
// Controller Only
// To handle routes like "/api/VTRouting"
config.Routes.MapHttpRoute(
name: "ControllerOnly",
routeTemplate: "api/{controller}"
);
有什么想法吗?我对返回类型行为感到困惑:-S