Почему моя страница Swagger index.html пуста после публикации?C#

Место общения программистов C#
Ответить
Anonymous
 Почему моя страница Swagger index.html пуста после публикации?

Сообщение Anonymous »

Я пишу веб-API ASP.NET Core. Моя среда — ASP.NET Core 5.0, в разработке используются Windows 10 и Visual Studio 19, в рабочей — Windows Server 2016 и IIS. Я занимаюсь разработкой на C# и реализую Swagger через Swashbuckle. Это мое первое приложение ASP.NET Core, поэтому я новичок.
Вот в чем дело: когда я запускаю проект из Visual Studio 19, просто появляется страница Swagger. как я ожидаю. Я публикую проект в папку и копирую эту папку в место назначения, которое настроено в IIS на локальном порту 35701. Когда я перехожу к http://localhost:35701/swagger/index.html, я получаю страницу с названием " Swagger UI», в противном случае страница пуста. Я получаю то же самое, если запускаю приложение .NET Core вне IIS и перехожу по адресу http://localhost:5000/swagger/index.html. Я также получаю такое же поведение, если публикую в режиме отладки или выпуска.
Я думаю, что это должно быть что-то в моей конфигурации, но я не могу понять, что именно.
Вот мой курс по стартапам:

Код: Выделить всё

    public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c => {
c.SwaggerDoc("v1", new OpenApiInfo { Title = "XoikosOnlineOrderingAPI", Version = "v1" });
string filePath = Path.Combine(System.AppContext.BaseDirectory, "XoikosOnlineOrderingAPI.xml");
c.IncludeXmlComments(filePath);
});
}

// This method gets called by the runtime.  Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
log4net.Config.XmlConfigurator.Configure();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "XoikosOnlineOrderingAPI v1"));

app.UseHttpsRedirection();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
Вот мой файл launchSettings.json:

Код: Выделить всё

{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:51728",
"sslPort": 0
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"XoikosOnlineOrderingAPI": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
Вот исходный код страницы пользовательского интерфейса Swagger, которую я получаю:

Код: Выделить всё





Swagger UI





html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}

*,
*:before,
*:after {
box-sizing: inherit;
}

body {
margin: 0;
background: #fafafa;
}








if (window.navigator.userAgent.indexOf("Edge") > -1) {
console.log("Removing native Edge fetch in favor of swagger-ui's polyfill")
window.fetch = undefined;
}





/* Source: https://gist.github.com/lamberta/3768814
* Parse a string function definition and return a function object.  Does not use eval.
* @param {string} str
* @return {function}
*
* Example:
*  var f = function (x, y) { return x * y; };
*  var g = parseFunction(f.toString());
*  g(33, 3); //=> 99
*/
function parseFunction(str) {
if (!str) return void (0);

var fn_body_idx = str.indexOf('{'),
fn_body = str.substring(fn_body_idx + 1, str.lastIndexOf('}')),
fn_declare = str.substring(0, fn_body_idx),
fn_params = fn_declare.substring(fn_declare.indexOf('(') + 1, fn_declare.lastIndexOf(')')),
args = fn_params.split(',');

args.push(fn_body);

function Fn() {
return Function.apply(this, args);
}
Fn.prototype = Function.prototype;

return new Fn();
}

window.onload = function () {
var configObject = JSON.parse('{"urls":[{"url":"/swagger/v1/swagger.json","name":"XoikosOnlineOrderingAPI v1"}],"deepLinking":false,"persistAuthorization":false,"displayOperationId":false,"defaultModelsExpandDepth":1,"defaultModelExpandDepth":1,"defaultModelRendering":"example","displayRequestDuration":false,"docExpansion":"list","showExtensions":false,"showCommonExtensions":false,"supportedSubmitMethods":["get","put","post","delete","options","head","patch","trace"],"tryItOutEnabled":false}');
var oauthConfigObject = JSON.parse('{"scopeSeparator":" ","scopes":[],"useBasicAuthenticationWithAccessCodeGrant":false,"usePkceWithAuthorizationCodeGrant":false}');

// Workaround for https://github.com/swagger-api/swagger-ui/issues/5945
configObject.urls.forEach(function (item) {
if (item.url.startsWith("http") || item.url.startsWith("/")) return;
item.url = window.location.href.replace("index.html", item.url).split('#')[0];
});

// If validatorUrl is not explicitly provided, disable the feature by setting to null
if (!configObject.hasOwnProperty("validatorUrl"))
configObject.validatorUrl = null

// If oauth2RedirectUrl isn't specified, use the built-in default
if (!configObject.hasOwnProperty("oauth2RedirectUrl"))
configObject.oauth2RedirectUrl = (new URL("oauth2-redirect.html", window.location.href)).href;

// Apply mandatory parameters
configObject.dom_id = "#swagger-ui";
configObject.presets = [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset];
configObject.layout = "StandaloneLayout";

// Parse and add interceptor functions
var interceptors = JSON.parse('{"RequestInterceptorFunction":null,"ResponseInterceptorFunction":null}');
if (interceptors.RequestInterceptorFunction)
configObject.requestInterceptor = parseFunction(interceptors.RequestInterceptorFunction);
if (interceptors.ResponseInterceptorFunction)
configObject.responseInterceptor = parseFunction(interceptors.ResponseInterceptorFunction);

// Begin Swagger UI call region

const ui = SwaggerUIBundle(configObject);

ui.initOAuth(oauthConfigObject);

// End Swagger UI call region

window.ui = ui
}



Я не уверен, какие еще подробности я могу добавить. Пожалуйста, спросите обо всем, что может пролить свет на то, что происходит. Любая помощь будет оценена. Спасибо.

Подробнее здесь: https://stackoverflow.com/questions/695 ... ublication
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»