ASP.NET Core HTTPRequestMessage returns strange JSON message

你。 提交于 2019-11-28 01:49:00

According to this article, ASP.NET Core MVC does not support HttpResponseMessage-returning methods by default.

If you want to keep using it, you can, by using WebApiCompatShim:

  1. Add reference to Microsoft.AspNetCore.Mvc.WebApiCompatShim to your project.
  2. Configure it in ConfigureServices(): services.AddMvc().AddWebApiConventions();
  3. Set up route for it in Configure():

    app.UseMvc(routes =>
    {
        routes.MapWebApiRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    

If you want to set Cache-Control header with string content, try this:

[Produces("text/plain")]
public string Tunnel()
{
    Response.Headers.Add("Cache-Control", "no-cache");
    return "blablabla";
}

In ASP.NET Core, modify the response as it travels through the pipeline. So for headers, set them directly as in this answer. (I've tested this for setting cookies.) You can also set the HTTP status code this way.

To set content, and therefore use a specific formatter, follow the documentation Format response data in ASP.NET Core Web API. This enables you to use helpers such as JsonResult() and ContentResult().

A complete example translating your code might be:

[HttpGet("tunnel")]
public ContentResult Tunnel() {
    var response = HttpContext.Response;
    response.StatusCode = (int) HttpStatusCode.OK;
    response.Headers[HeaderNames.CacheControl] = CacheControlHeaderValue.NoCacheString;
    return ContentResult("blablabla", "text/plain", Encoding.UTF8);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!