Welcome to mirror list, hosted at ThFree Co, Russian Federation.

UseEndpointRoutingStartup.cs « RoutingWebSite « testassets « test « Routing « Http « src - github.com/dotnet/aspnetcore.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 62744ce1e07dbed578e3b53e581449a5555420ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.Internal;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Internal;
using Microsoft.AspNetCore.Routing.Patterns;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace RoutingWebSite;

public class UseEndpointRoutingStartup
{
    private static readonly byte[] _plainTextPayload = Encoding.UTF8.GetBytes("Plain text!");

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<EndsWithStringRouteConstraint>();

        services.AddRouting(options =>
        {
            options.ConstraintMap.Add("endsWith", typeof(EndsWithStringRouteConstraint));
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        app.UseRouting();

        app.Map("/Branch1", branch => SetupBranch(branch, "Branch1"));
        app.Map("/Branch2", branch => SetupBranch(branch, "Branch2"));

        // Imagine some more stuff here...

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHello("/helloworld", "World");

            endpoints.MapGet(
                "/",
                (httpContext) =>
                {
                    var dataSource = httpContext.RequestServices.GetRequiredService<EndpointDataSource>();

                    var sb = new StringBuilder();
                    sb.AppendLine("Endpoints:");
                    foreach (var endpoint in dataSource.Endpoints.OfType<RouteEndpoint>().OrderBy(e => e.RoutePattern.RawText, StringComparer.OrdinalIgnoreCase))
                    {
                        sb.AppendLine(FormattableString.Invariant($"- {endpoint.RoutePattern.RawText}"));
                    }

                    var response = httpContext.Response;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    return response.WriteAsync(sb.ToString());
                });
            endpoints.MapGet(
                "/plaintext",
                (httpContext) =>
                {
                    var response = httpContext.Response;
                    var payloadLength = _plainTextPayload.Length;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    response.ContentLength = payloadLength;
                    return response.Body.WriteAsync(_plainTextPayload, 0, payloadLength);
                });
            endpoints.MapGet(
                "/convention",
                (httpContext) =>
                {
                    var endpoint = httpContext.GetEndpoint();
                    return httpContext.Response.WriteAsync((endpoint.Metadata.GetMetadata<CustomMetadata>() != null) ? "Has metadata" : "No metadata");
                }).Add(b =>
                {
                    b.Metadata.Add(new CustomMetadata());
                });
            endpoints.MapGet(
                "/withconstraints/{id:endsWith(_001)}",
                (httpContext) =>
                {
                    var response = httpContext.Response;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    return response.WriteAsync("WithConstraints");
                });
            endpoints.MapGet(
                "/withoptionalconstraints/{id:endsWith(_001)?}",
                (httpContext) =>
                {
                    var response = httpContext.Response;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    return response.WriteAsync("withoptionalconstraints");
                });
            endpoints.MapGet(
                "/WithSingleAsteriskCatchAll/{*path}",
                (httpContext) =>
                {
                    var linkGenerator = httpContext.RequestServices.GetRequiredService<LinkGenerator>();

                    var response = httpContext.Response;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    return response.WriteAsync(
                        "Link: " + linkGenerator.GetPathByRouteValues(httpContext, "WithSingleAsteriskCatchAll", new { }));
                }).WithMetadata(new RouteNameMetadata(routeName: "WithSingleAsteriskCatchAll"));
            endpoints.MapGet(
                "/WithDoubleAsteriskCatchAll/{**path}",
                (httpContext) =>
                {
                    var linkGenerator = httpContext.RequestServices.GetRequiredService<LinkGenerator>();

                    var response = httpContext.Response;
                    response.StatusCode = 200;
                    response.ContentType = "text/plain";
                    return response.WriteAsync(
                        "Link: " + linkGenerator.GetPathByRouteValues(httpContext, "WithDoubleAsteriskCatchAll", new { }));
                }).WithMetadata(new RouteNameMetadata(routeName: "WithDoubleAsteriskCatchAll"));

            MapHostEndpoint(endpoints);
            MapHostEndpoint(endpoints, "*.0.0.1");
            MapHostEndpoint(endpoints, "127.0.0.1");
            MapHostEndpoint(endpoints, "*.0.0.1:5000", "*.0.0.1:5001");
            MapHostEndpoint(endpoints, "contoso.com:*", "*.contoso.com:*");
        });
    }

    private class CustomMetadata
    {
    }

    private IEndpointConventionBuilder MapHostEndpoint(IEndpointRouteBuilder endpoints, params string[] hosts)
    {
        var hostsDisplay = (hosts == null || hosts.Length == 0)
            ? "*:*"
            : string.Join(",", hosts.Select(h => h.Contains(':') ? h : h + ":*"));

        var conventionBuilder = endpoints.MapGet(
            "api/DomainWildcard",
            httpContext =>
            {
                var response = httpContext.Response;
                response.StatusCode = 200;
                response.ContentType = "text/plain";
                return response.WriteAsync(hostsDisplay);
            });

        conventionBuilder.Add(endpointBuilder =>
        {
            endpointBuilder.Metadata.Add(new HostAttribute(hosts));
            endpointBuilder.DisplayName += " HOST: " + hostsDisplay;
        });

        return conventionBuilder;
    }

    private void SetupBranch(IApplicationBuilder app, string name)
    {
        app.UseRouting();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("api/get/{id}", (context) => context.Response.WriteAsync($"{name} - API Get {context.Request.RouteValues["id"]}"));
        });
    }
}