Failed to load API definition Fetch Error, when deployed but fine on localhost - azure-devops

I am upgrading my api from netcore2.1 to 3.1
When I run on localhost the UI works fine.
When I deploy via Azure DevOps and go to the myapplication/myapi/swagger.html url I get
Failed to load API definition
Fetch Error
Service Unavailable /myapi/swagger/v1/swagger/json
Yet I can see the json at
myapplication/myapi/swagger/v1/swagger.json
I have the following
public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
{
app.UseSwagger(c =>
c.RouteTemplate = "myapi/swagger/{documentName}/swagger.json"
);
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/myapi/swagger/v1/swagger.json", "Versioned API v1.0");
c.RoutePrefix = "myapi/swagger";
});
return app;
}
I am using
Swashbuckle.AspNetCore (5.2.0)

I found the following worked.
public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app)
{
app.UseSwagger(c =>
c.RouteTemplate = "myapi/{documentName}/swagger.json"
);
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("./v1/swagger.json", "Versioned API v1.0");
c.RoutePrefix = "myapi";
});
return app;
}
The docs state
If using directories with IIS or a reverse proxy, set the Swagger
endpoint to a relative path using the ./ prefix. For example,
./swagger/v1/swagger.json. Using /swagger/v1/swagger.json instructs
the app to look for the JSON file at the true root of the URL (plus
the route prefix, if used). For example, use
http://localhost://swagger/v1/swagger.json instead
of
http://localhost:///swagger/v1/swagger.json.
However unfortunately my solution doesn't work with Autorest.
Thus I asked another question

Related

No API definition provided. - openApi - springdoc

I have a simple boot application where I have added open api swagger dependency
springdoc-openapi-ui
along with these properties
springdoc.swagger-ui.disable-swagger-default-url=true
springdoc.swagger-ui.configUrl=/v3/api-docs/swagger-config
springdoc.swagger-ui.path=/swagger-ui.html
I am getting these error (when calling http://localhost:8080/swagger-ui/index.html):
No API definition provided.
this is my controller :
#RestController
public class HelloWorld {
#GetMapping("sayHi")
public String sayHi(){
return "Hi Beno";
}
}
Any idea ?
When using a different endpoint to serve the OpenAPI Config, you'll need to set two properties
// This will set UI to fetch the config's URL from "somePath"
springdoc.swagger-ui.configUrl=somePath
// You also need to serve the config file from the endpoint at "somePath"
springdoc.api-docs.path=somePath

ECONNREFUSED during 'next build'. Works fine with 'next dev' [duplicate]

This question already has an answer here:
Fetch error when building Next.js static website in production
(1 answer)
Closed last year.
I have a very simple NextJS 9.3.5 project.
For now, it has a single pages/users and a single pages/api/users that retrieves all users from a local MongoDB table
It builds fine locally using 'next dev'
But, it fails on 'next build' with ECONNREFUSED error
page/users
import fetch from "node-fetch"
import Link from "next/link"
export async function getStaticProps({ params }) {
const res = await fetch(`http://${process.env.VERCEL_URL}/api/users`)
const users = await res.json()
return { props: { users } }
}
export default function Users({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
<Link href="/user/[id]" as={`/user/${user._id}`}>
<a>{user.name}</a>
</Link>
</li>
))}
</ul>
);
}
pages/api/users
import mongoMiddleware from "../../lib/api/mongo-middleware";
import apiHandler from "../../lib/api/api-handler";
export default mongoMiddleware(async (req, res, connection, models) => {
const {
method
} = req
apiHandler(res, method, {
GET: (response) => {
models.User.find({}, (error, users) => {
if (error) {
connection.close();
response.status(500).json({ error });
} else {
connection.close();
response.status(200).json(users);
}
})
}
});
})
yarn build
yarn run v1.22.4
$ next build
Browserslist: caniuse-lite is outdated. Please run next command `yarn upgrade`
> Info: Loaded env from .env
Creating an optimized production build
Compiled successfully.
> Info: Loaded env from .env
Automatically optimizing pages ..
Error occurred prerendering page "/users". Read more: https://err.sh/next.js/prerender-error:
FetchError: request to http://localhost:3000/api/users failed, reason: connect ECONNREFUSED 127.0.0.1:3000
Any ideas what is going wrong ? particularly when it works fine with 'next dev' ?
Thank you.
I tried the same few days ago and didn't work... because when we build the app, we don't have localhost available... check this part of the doc - https://nextjs.org/docs/basic-features/data-fetching#write-server-side-code-directly - that said: "You should not fetch an API route from getStaticProps..." -
(Next.js 9.3.6)
Just to be even more explicit on top of what Ricardo Canelas said:
When you do next build, Next goes over all the pages it detects that it can build statically, i.e. all pages that don't define getServerSideProps, but which possibly define getStaticProps and getStaticPaths.
To build those pages, Next calls getStaticPaths to decide which pages you want to build, and then getStaticProps to get the actual data needed to build the page.
Now, if in either of getStaticPaths or getStaticProps you do an API call, e.g. to a JSON backend REST server, then this will get called by next build.
However, if you've integrated both front and backend nicely into a single server, chances are that you have just quit your development server (next dev) and are now trying out a build to see if things still work as sanity check before deployment.
So in that case, the build will try to access your server, and it won't be running, so you get an error like that.
The correct approach is, instead of going through the REST API, you should just do database queries directly from getStaticPaths or getStaticProps. That code never gets run on the client anyways, only server, to it will also be slightly more efficient than doing a useless trip to the API, which then calls the database indirectly. I have a demo that does that here: https://github.com/cirosantilli/node-express-sequelize-nextjs-realworld-example-app/blob/b34c137a9d150466f3e4136b8d1feaa628a71a65/lib/article.ts#L4
export const getStaticPathsArticle: GetStaticPaths = async () => {
return {
fallback: true,
paths: (await sequelize.models.Article.findAll()).map(
article => {
return {
params: {
pid: article.slug,
}
}
}
),
}
}
Note how on that example, both getStaticPaths and getStaticProps (here generalized HoC's for reuse, see also: Module not found: Can't resolve 'fs' in Next.js application ) do direct database queries via sequelize ORM, and don't do any HTTP calls to the external server API.
You should then only do client API calls from the React components on the browser after the initial pages load (i.e. from useEffect et al.), not from getStaticPaths or getStaticProps. BTW, note that as mentioned at: What is the difference between fallback false vs true vs blocking of getStaticPaths with and without revalidate in Next.js SSR/ISR? reducing client calls as much as possible and prerendering on server greatly reduces application complexity.

After Deploying, ASP.NET application showing Internal server error

I deployed my ASP.NET application to a remote server with a hosting company, and when i try to send data from Postman, i get the internal server error with no definite error message. I have set custom error mode to off in the web config file. please can anyone help me? I have checked for several solutions but nothing.
PS: i am new to ASP.NET deployment with other companies apart from Azure
In this case, you should log error to file to see what issues in deployment mode.
This way i implemented global error log.
public class ExceptionHandlingAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
//Log Critical errors
// You can use log4net library and configure log folder
}
}
In WebApiConfig.cs file you register it.
public static void Register(HttpConfiguration config)
{
// .....
config.Filters.Add(new ExceptionHandlingAttribute());
}

host more than one app under one website entry in IIS

i have created sample rest service which just return xml
its work fine in my development environment
[RouteAttributes(UriTemplate = "{appname}/adfsapi/mex")]
public class SAMLMexRouteHandler : IRouteHandler
{
}
where app name will be change, and my url
http://localhost:64219/test/adfsapi/mex
till here everything fine
but when i hosting app to IIS
than trying to call my rest service url
http://localhost:8089/testapp1/adfsapi/mex
its throwing 404 not found error .
any suggestion which step i am doing wrong.
Thanks
i solved the issue by converting to application for every directory .
and my URI will be like this -
[RouteAttributes(UriTemplate = "adfsapi/mex")]
public class SAMLMexRouteHandler : IRouteHandler
{
}

authentication with Xamarin. Android and Microsoft.Azure.Mobile.Client Microsoft provider error

I had a code that worked unlit few days ago: this is an xamarin.android activity code
[Activity(Label = "AuthSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
Button login;
//Mobile Service Client reference
private MobileServiceClient client;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
client = new MobileServiceClient("https://XXXXXXX.azurewebsites.net");
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
login = FindViewById<Button>(Resource.Id.buttonLoginUser);
login.Click += onLoginClick;
}
private async void onLoginClick(object sender, EventArgs e)
{
// Load data only after authentication succeeds.
if (await Authenticate())
{
}
}
// Define a authenticated user.
private MobileServiceUser user;
private async Task<bool> Authenticate()
{
var success = false;
try
{
// Sign in with Microsoft login using a server-managed flow.
user = await client.LoginAsync(this,
MobileServiceAuthenticationProvider.MicrosoftAccount);
CreateAndShowDialog(string.Format("you are now logged in - {0}",
user.UserId), "Logged in!");
success = true;
}
catch (Exception ex)
{
CreateAndShowDialog(ex, "Authentication failed");
}
return success;
}
private void CreateAndShowDialog(Exception exception, String title)
{
CreateAndShowDialog(exception.Message, title);
}
private void CreateAndShowDialog(string message, string title)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.SetMessage(message);
builder.SetTitle(title);
builder.Create().Show();
}
}
i did all the instruction in the tutorial.
the LoginAsync redirect me to the Microsoft login page, i am able to authenticate and after a successful authentication i get this error : "the page cannot be displayed because an internal server error has occured"
i am working with 3.1 azure sdk version
According to your description, I assumed that you could follow the steps below to troubleshoot this issue.
For Node.js backend
You could leverage App Service Editor or kudu for create the iisnode.yml file under root folder (D:\home\site\wwwroot) if not exists. Then add the following settings for enable logging to debug a Node.js web app in azure app service:
loggingEnabled: true
logDirectory: iisnode
Additionally, here is a similar issue about enable node.js logging, you could refer to it. Also, for more details about kudu and app service editor, you could refer to here.
For C# backend
you could edit App_Start\Startup.MobileApp.cs file and configure the IncludeErrorDetailPolicy as follows for capturing the error details:
HttpConfiguration config = new HttpConfiguration();
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
For a simple way, you could access https://{your-app-name}.azurewebsites.net/.auth/login/{provider-name} via the browser, then check the detailed error message for locating the specific error.
UPDATE:
Based on your address, I checked your app and found I could log with my Microsoft Account via the browser. Then I checked with your table endpoint and found the follow error:
https://{your-app-name}.azurewebsites.net/tables/todoitem?ZUMO-API-VERSION=2.0.0
message: "An error has occurred.",
exceptionMessage: "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 52 - Unable to locate a Local Database Runtime installation. Verify that SQL Server Express is properly installed and that the Local Database Runtime feature is enabled.)",
exceptionType: "System.Data.SqlClient.SqlException",
As I known, when following the quickstart to create the data store for your backend, downloading the C# backend, then deploy the backend to moible app. At this point, your created connection string via azure portal would not be exposed to your ASP.NET application, and the default connection string would use the localdb, you need to edit the Web.config file before deploying to azure mobile app as follows:
<connectionStrings>
<add name="MS_TableConnectionString" connectionString="Data Source=tcp:{your-sqlserver-name}.database.windows.net,1433;Initial Catalog={db-name};User ID={user-id};Password={password}" providerName="System.Data.SqlClient" />
</connectionStrings>
Or configure the connection string when deploy your app to azure mobile app via VS as follows:
It seems that there was a problem in azure or in Microsoft authentication.
after two days of frustration everything just started to work again!!