How can I configure a route for WebApiConfig to redirect some requests to static html page?

此生再无相见时 提交于 2019-12-08 00:10:48

问题


I'm working on a webApi application, and the api I want to get is the following:

  • api/v1/lists/?params...
  • api/v1/meta/?params...
  • api/v1/debug

There are ApiControllers that work fine for "lists" and "meta" routes, but api/v1/debug should return a static html page.

I could think of two ways of implementing it:

  1. via special controller that would return something like View("mypage.html") or
  2. configure routes in WebApiConfig to redirect requests like api/v1/debug to mypage.html

However, I couldn't get working version of any of these ways: there is no content type for HttpResponseMessage like HtmlContent or similar, so I can't do smth like

config.Routes.MapHttpRoute(
    name: "Debug",
    routeTemplate: "api/v1/debug/",
    defaults: new { controller = "Debug" }
    );

...

public class DebugController:ApiController
{
    public HttpResponseMessage Get()
    {
        return new HttpResponseMessage()
        {
            Content = new HtmlContent("mypage.html");
        };
    }
}

and I can't get right redirection in WebApiConfig:

//this results into 400 status code:
config.Routes.MapHttpRoute("Default", "api/v1/debug/", "~/mypage.html");

Could you please tell me what would be the right solution for this problem? And is it possible at all to combine static html pages with Action Results in WebApi application?


回答1:


The best option is to use MVC for rendering html pages. WebAPI and MVC can live together. Note that they use different route types.

As a quick hack (using WebAPI), you can read a file and write its contents to HttpResponseMessage like this:

// this is a controller method
public HttpResponseMessage CreateResponseFromFile()
    {
        var content = File.ReadAllText("yourfile.html");
        if (content == null)
            throw new HttpResponseException(HttpStatusCode.NoContent);

        var response = new HttpResponseMessage
        {
            Content = new StringContent(content)
        };
        response.Content.Headers.Add("Content-Type", "  text/html");  // note this line to set content type
        return response;
    }



回答2:


Well, I've found another way to get what I want, so I'll just leave it here in case it could help someone.

Kind of dirty hack that could help to follow general route rules is to add the following section in your web.config:

<configuration>
  <system.web>
    <urlMappings enabled="true">
      <add url="~/api/v1/debug/" mappedUrl="~/mypage.html" />
    </urlMappings>
  </system.web>
</configuration>


来源:https://stackoverflow.com/questions/27406245/how-can-i-configure-a-route-for-webapiconfig-to-redirect-some-requests-to-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!