ASP NET Core服务特定的html页面 [英] ASP NET Core Serving specific html page

查看:63
本文介绍了ASP NET Core服务特定的html页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个中间件:

 公共类SpecificPageMiddleware{私有只读RequestDelegate接下来;public SpecificPageMiddleware(下一个RequestDelegate){this.next =下一个;}公共异步任务调用(HttpContext上下文){如果(this.IsSubDomainRequest(context.Request.Host.Value)){如果(this.IsIndexRequest(context.Request.Path.Value)){等待this.ReturnIndexPage(context);返回;}}等待this.next.invoke(context);}私人布尔IsSubDomainRequest(字符串主机){返回host.StartsWith("subdomain")||host.Contains("subdomain");}私人布尔IsIndexRequest(字符串查询){返回查询=="/" ||查询=="/response.html";}私有静态异步任务ReturnIndexPage(HttpContext context){var file = new FileInfo(@"wwwroot \ response.html");byte []缓冲区;如果(file.exists){context.Response.StatusCode =(int)HttpStatusCode.OK;context.Response.ContentType ="text/html";缓冲区= File.ReadAllBytes(file.FullName);}别的{context.Response.StatusCode =(int)HttpStatusCode.NotFound;context.Response.ContentType =文本/纯文本";缓冲区= Encoding.UTF8.GetBytes(无法找到所请求的文件");}使用(var stream = context.Response.Body){等待stream.WriteAsync(buffer,0,buffer.Length);等待stream.FlushAsync();}context.Response.ContentLength = buffer.Length;}} 

很简单,当我通过 subdomain.mydomain.com 得到类似的信息时,我想显示一个特定的html页面,否则继续进行正常的中间件流水线访问 www.mydomain.com.

当该中间件被点击时,它最终在浏览器中显示为404.如果我未设置内容类型,则最终将其显示为200,而所有html均写为文本,而不是呈现为html.我在这里想念什么?

我不想使用 app.UseDefaultFiles() app.UseStaticFiles().

解决方案

答案.

您犯的一个错误是在这里:

 正在等待.//错误的!等待SpecificPageMiddleware.ReturnIndexPage(context);//对(1)等待ReturnIndexPage(context);//正确(2) 

是实例.您无法从实例访问 static 方法.相反,您必须使用类型名称(1)或没有任何限定(2)对其进行限定,就可以了.

在我的机器上工作

出于良好的考虑,

I have this middleware:

public class SpecificPageMiddleware
{
    private readonly RequestDelegate next;

    public SpecificPageMiddleware(RequestDelegate next)
    {
        this.next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        if (this.IsSubDomainRequest(context.Request.Host.Value)) 
        {
            if (this.IsIndexRequest(context.Request.Path.Value)) 
            {
                await this.ReturnIndexPage(context);
                return;
            }
        }

        await this.next.Invoke(context);
    }

    private bool IsSubDomainRequest(string host)
    {
        return host.StartsWith("subdomain")
                || host.Contains("subdomain");
    }

    private bool IsIndexRequest(string query)
    {
        return query == "/" || query == "/response.html";
    }

    private static async Task ReturnIndexPage(HttpContext context)
    {
        var file = new FileInfo(@"wwwroot\response.html");
        byte[] buffer;
        if (file.Exists)
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;
            context.Response.ContentType = "text/html";

            buffer = File.ReadAllBytes(file.FullName);
        }
        else
        {
            context.Response.StatusCode = (int)HttpStatusCode.NotFound;
            context.Response.ContentType = "text/plain";

            buffer = Encoding.UTF8.GetBytes("Unable to find the requested file");
        }

        using (var stream = context.Response.Body)
        {
            await stream.WriteAsync(buffer, 0, buffer.Length);
            await stream.FlushAsync();
        }

        context.Response.ContentLength = buffer.Length;
    }
}

Quite simply, when I get something like this through: subdomain.mydomain.com I want to show a specific html page otherwise carry on the normal middleware pipeline to www.mydomain.com.

When this middleware gets hit, it ends up as a 404 in the browser. If I don't set a content type then it ends up as 200 with all the html written out as text, rather then rendered as html. What am I missing here?

I don't want to use app.UseDefaultFiles() or app.UseStaticFiles().

解决方案

Answer.

One mistake you're making is here:

await this.ReturnIndexPage(context);                      // wrong!
await SpecificPageMiddleware.ReturnIndexPage(context);    // right (1)
await ReturnIndexPage(context);                           // right (2)

this means the instance. You cannot access a static method from the instance. Instead you have to qualify it with a type name (1) or with no qualification (2) and you're fine.

Works on my machine

For good measure, this is up on GitHub too as a demo.

SimpleMiddleware.cs

using Microsoft.AspNet.Builder;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using System.IO;
using System.Text;
using System.Net;

namespace App04SimpleMiddleware
{
    public class SimpleMiddleware
    {
        private readonly RequestDelegate _next;
        public SimpleMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            if (context.Request.QueryString.ToString().Contains("simple"))
            {
                await ReturnIndexPage(context);          // right! 
                return;
            }
            await _next.Invoke(context);
        }

        private static async Task ReturnIndexPage(HttpContext context)
        {
            var file = new FileInfo(@"wwwroot\response.html");
            byte[] buffer;
            if (file.Exists)
            {
                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "text/html";

                buffer = File.ReadAllBytes(file.FullName);
            }
            else
            {
                context.Response.StatusCode = (int)HttpStatusCode.NotFound;
                context.Response.ContentType = "text/plain";
                buffer = Encoding.UTF8
                    .GetBytes("Unable to find the requested file");
            }

            context.Response.ContentLength = buffer.Length;

            using (var stream = context.Response.Body)
            {
                await stream.WriteAsync(buffer, 0, buffer.Length);
                await stream.FlushAsync();
            }    
        }
    }
}

Startup.cs

using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;

namespace App04SimpleMiddleware
{
    public class Startup
    {   
        public void Configure(IApplicationBuilder app)
        {
            app.UseMiddleware<SimpleMiddleware>();            
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello world!");
            });
        }
    }
}

Result

这篇关于ASP NET Core服务特定的html页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆