Swagger run locally but not on IIS, not resolving base path - json

I am setting up Swagger for documenting my API.
I have set up the SwaggerEndpoint with a relative path the the specification json, like you see below:
When I debug locally, everything resolves fine. But my site just runs as http://localhost:44348/index.html.
When I deploy to IIS, which is on a virtual path, it blows apart:
Note that the URL in the browser has /imaging4castapi_UAT/ as part of the path
Note that the actual request for the swagger.json is missing that base part of the path.
Here's what I've tried:
I tried removing the RoutePrefix override. But that doesn't resolve.
I tried using an application path like "~/swagger/..." but that's translated by the server on view elements like Razor pages and css and doesn't work here in Startup.
I'm struggling to understand if this is a client setup issue or something related to how my site is hosted on IIS.
Thoughts?

Try using a relative path:
setupAction.SwaggerEndpoint("../swagger/Imaging4CastApiSpecification/swagger.json", "4Cast API");
Please note answer and explanation from the following issue: SwashBuckle

Here is my Swagger config for once of PRD application. Hope it helps
public static IServiceCollection AddSwaggerConfig(this IServiceCollection services, IHostingEnvironment env,
string title, string version)
=> services.AddSwaggerGen(c =>
{
//Ensure XML Document File of project is checked for both Debug and Release mode
c.IncludeXmlComments("Your App.xml");
//Display Enum name
c.DescribeAllEnumsAsStrings();
//c.OperationFilter<AddRequiredHeaderParameter>();
//Authentication for Bearer
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter JWT with Bearer into field",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", Enumerable.Empty<string>()}
});
c.SwaggerDoc(version, new Info
{
Title = title,
Version = version,
Description = "",
Contact = new Contact
{
Email = "Support#ABC.com",
Name = ""
}
});
});
Startup file
app.
//Swagger
.UseSwagger()
.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./{_version}/swagger.json", Title);
});
The version is app variable from Config file which will be filtered by CI/CD

Swagger does not support Virtual Directory by default. Try and add this to your Startup.cs
app.UseSwagger(c =>
{
c.RouteTemplate = "virtual_path/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
//Include virtual directory
c.RoutePrefix = "virtual_path";// add your virtual path here.
c.SwaggerEndpoint("v1/swagger.json", "Api v1");
});

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint($"./v1/swagger.json", "Api v1");
});

My fix was following Killnines last comment to remove the preceding forward slash so that it looks like the following;
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("swagger/v1/swagger.json", "Your API v1");
});

Related

How to get the Configuration App Settings file in MAUI iOS

I am converting my Xamarin Forms Application to .NET MAUI.
In existing application I am using below code which is using Xamarin.iOS to fetch the config file(App.config) which is in xml format and has app settings
public string Path
{
get
{
try
{
return System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
}
catch
{
throw new FileNotFoundException(#"File not found.");
}
}
}
But the same code doesn't work in MAUI
I tried below approach but File.OpenRead(Path) is throwing error "Data at the root level is invalid. Line 1, position 1"
App.config file is added in path Projectname/Platforms/iOS/App.config
public string Path
{
get
{
try
{
string configPath = string.Empty;
configPath = Assembly.GetEntryAssembly().Location + ".config";
AppDomain domain = System.AppDomain.CurrentDomain;
configPath = System.IO.Path.Combine(domain.SetupInformation.ApplicationBase, domain.FriendlyName + ".config");
return configPath;
}
catch
{
throw new FileNotFoundException(#"File not found.");
}
}
}
Any help is appreciated!
Since the value of Path could be obtained, you could manually checked the content to see if it is the one you want.
From the thrown error "Data at the root level is invalid. Line 1, position 1", it seems something wrong with xml data load. Some issues similar to this question indicated that it may due to BOM character, take a look at this issue.
Actually we could use appsettings.json as an alternative, see this App Configuration Settings in .NET MAUI and github project. It's really easy to read app config in this way.

How can I show image from express server on Vue app?

I'm currently having problem with displaying image from db. In my DB (Sequelize MySQL), my columns looks like this.
Database
You can see that there is path, which is showing path to file on server. (Express server using multer to upload photos).
How Am I able to show this on my frontend? I was trying everything, but I cannot figure solution.
When I open my server folder and copy path of file there, I get path like this:
Path
When I put it in chrome, I can see that image, but when I try to display it in frontend, I'm not that lucky.
Here is my function on backend to get image.
async getOneImage (req,res){
try{
const getOneImage = await CaseImage.findOne({ where: {CaseId: req.params.CaseId, id: req.params.id}});
if (getOneImage == null) {
res.status(400).send({ message: 'Prípad so zadaným ID sa nenašiel.' });
}
res.send(getOneImage);
}
catch (err) {
console.log(err);
res.status(400).send({ message: 'Nepodarilo sa načítať fotografie, skúste to neskôr.'});
}
},
Maybe should I change that response to binary or? I don't understand this topic cleary as you can see.
Thank you all for help and sorry if question is not correctly formated or named.
Ok so I tried, now I have request to node server but I get response 404 cannot get... so I'm assuming that problem is somewhere in my express settings...
this.imageSrc = http://localhost:3000/${data.path}.png
this is full url.. but response is 404.
http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png
edit.
So, this is my front-end.. You can see that I'm sending response to correct path.
frontend request
Here you can see how my backend setting of express looks like.
Express
And here is response that I'm getting when I send request to backend.
Response
But I'm still not able to see image in vue. When I check I see only blank space and in console is this reply:
"GET http://localhost:3000/static/uploads/70e13f7cd5e6a3d0a0d0bc252d62fa31.png 404 (Not Found)"
And in network tab is this.
Network tab
If you have correct paths to the images in your database you simply render them with an tag. Make sure the path to the file is complete, or relative to your static assets folder.
In your case the path seems to be some mix of static/uploads/hash and the filename problem.png.
This means the full url to the file is most likely something like:
domain.com/static/uploads//.png. The domain.com part will most likely be localhost: if you are working locally. On a production server this will be your domain you are hosting your app on.
PS. your second image is a full file path on your system, this wont be visible on a server.
So you have this static folder.
If you are not already serving this static folder with express, see this explanation on how to serve a static folder.
Once you fetch your image in the frontend you will have an image object something like this:
{
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
}
Your img tag in your html file should look as follows.
<img src="http://localhost:{PORT_OF_EXPRESS_SERVER}/static/uploads/abcdefg.........png"/>
Because you're using vue.js here is an example with axios.
MyComponent.js
import axios from 'axios';
export default {
data: () => {
return {
imageUrl: ''
}
},
mounted(): async () => {
// this route here must match what you defined in your backend
const { data } = await axios.get('/image/2/5')
console.log(data);
/** {
"id": 1,
"fileName": "problem.png",
"mimeType". "image/png",
"caseId: 2,
"path": "static/uploads/abcdefg.......png"
} **/
// now we set the imageUrl, assuming your express port is 1337
this.imageUrl = `http://localhost:1337/${data.path}`;
}
}
MyComponent.html
<template>
<div id="my-component">
<img :src="imageUrl"/>
</div>
</template>
<script src="./MyComponent.js"></script>

vuejs: the correct path of local json file for axios get request

In my Vue project, I have mocked some data for next step development. I already save the test data in a json file. And my vue project is typical one created with Vue-Cli, and the structure for my project goes as following:
My_project
build
config
data
service_general_info.json
node_modules
src
components
component-A
component-A.vue
as you can see, all the folders are created by the vue-cli originally. And I make a new folder data and place the test data json file inside.
And I want to read in the data by axios library in an event handling function inside the component of component-A as following:
methods: {
addData() {
console.log('add json data...');
axios.get('./../../data/service_general_info.json');
},
},
I use relative path to locate the target file.But get 404 error back. So how to set the path correctly? Currently I am running the dev mode in local host.
The error message is: GET http://localhost:8080/data/service_general_info.json 404 (Not Found)
In Vue-cli project, axios can't get data from custom folder.
You should use static folder to save test json file.
So you should change axios call like this:
axios.get('/static/service_general_info.json');
This will get data from json.
If you are doing just for sake of testing then you can save it in public folder and access it directly on http root.
e.g. I have the file results.json in public folder then I can access it using http://localhost:8080/results.json
For me it didn't work using static folder. I had to put it in public folder.
I put json folder in public & then accessed it like below.
getCountries() {
return axios.get('json/country-by-abbreviation.json', { baseURL: window.location.origin })
.then((response) => { return response.data; })
.catch((error) => {
throw error.response.data;
});
}
When the http call is made from the server, axios has no idea that you're on http://localhost:8080, you have to give the full url.
Like this:
methods: {
addData() {
console.log('add json data...');
axios.get('http://localhost:8080/data/service_general_info.json');
},
},
I had this same issue, only the above solutions wouldn't work as it is being uploaded to a subdirectory. I found I needed to put it in the public/assets folder and use:
axios.get(process.env.BASE_URL+'assets/file.json')
While in vue.config.js I have set the local and live paths
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/path/to/app/'
: '/'
}
You can simply read a static JSON file using import. Then assign in data.
import ServiceInfo from './../../data/service_general_info.json';
export default{
data(){
return {
ServiceInfo
}
}
}

Collection+JSON with AngularJS

I'm working on a project where various tables of data will be displayed with AngularJS. The data will be in the Collection+JSON format, as shown below. I found this library https://github.com/Medycation/angular-collection-json, I'm not sure how to make it work. Below is an example of the data.
angular.module('app', ['cj']);
var $injector = angular.injector();
var cj = $injector.get('cj');
cj("cjapi1.php").then(function(cjProvider){
console.log(collection.items());
});
I tried the above. In the console it says I need to register cjProvider as a provider. Any help with how to set this up properly would be appreciated. Thanks.
{
“collection”:
{
“version”: “0.1”,
“href” : “https://example.com/companies”
“items” : [
{
“href” : “https://example.com/companies/123”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 1”}
}
},
{
“href” : “https://example.com/companies/1234”,
“data” : [
{
“orgInfo”: {
{“name”: “companyName”, “value”: “Example Company 2”}
}
},
]
}
Please configure your cjProvider while configuring your module. Check the below code template for the reference to configure cjProvider.
angular.module('app', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});
Please make sure that you have configured your transformUrl just shown above.
Your base url must be configured in cjProvider and while hitting any url ang getting data you should transform your request like here you are requesting cjapi1.php. so your baseurl must be append before that like your_base_url + 'cjapi1.php' this will be done for all requesting api. So cjProvider will take care that and will return api path and in .then(responce) you will get your responce which is collection.
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
Are you trying to configure or get the contents of the collection from php call?
Looks like a typo to me but try this to get collection:
cj("cjapi1.php").then(function(collection){
console.log(collection.items());
});
...and this for configuration of your provider:
angular.module('agile', ['cj']).configure(function(cjProvider){
// Alter urls before they get requested
// cj('http://example.com/foo') requests http://example.com/foo/improved
cjProvider.setUrlTransform(function(original){
return original + '/improved';
});
// Disable strict version checking (collections without version "1.0")
cjProvider.setStrictVersion(false);
});

Play 2.0 routes file for different configurations

I have a Play 2.0 application with 3 different configurations (application.conf, test.conf and prod.conf)
Now I have a robots.txt file that should be delivered for only test.conf and for the rest environments it should give a 404 if someone tries to access it.
How can I configure my routes file to check if my application is using test.conf? Can I set some variable in test.conf that I can check in the routes file?
Something like this? (pseudo code)
#{if environment = "test"}
GET /robots.txt controllers.Assets.at(path="/public", file="robots.txt")
#{/if}
#{else}
GET /robots.txt controllers.Application.notFoundResult()
#{/else}
You can't add logic in the routes file.
I'd write a controller to serve the robots.txt file. Something like this:
In the routes file:
GET /robots.txt controllers.Application.robots
Then, in the controller, I'll test if I'm in a testing environment :
def robots = Action {
if (environment == "test") { // customize with your method
Redirect(routes.Assets.at("robots.txt"))
} else {
NotFound("")
}
}
I'm using Scala, but it can be easily translated to Java.
Edit - java sample
You can check if application is in one of three states: prod, dev or test, ie, simple method returning current state:
private static String getCurrentMode() {
if (play.Play.isTest()) return "test";
if (play.Play.isDev()) return "dev";
if (play.Play.isProd()) return "prod";
return "unknown";
}
you can use as:
play.Logger.debug("Current mode: "+ getCurrentMode());
of course in your case that's enough to use these condition directly:
public static Result robots() {
return (play.Play.isProd())
? notFound()
: ok("User-agent: *\nDisallow: /");
}