We are using Swashbuckle to generate a swagger 2.0 json, using C# on Asp .Net 4.5 (not Asp .Net core). I am trying to adapt our solution to generate openApi 3.0:
I understand that Swashbuckle for .Net 4.5 currently does not support openApi 3.0
I tried using nSwag, but it seems that the openApi that is generated is always 2.0, regardless of using the function UseSwaggerUi3, or using GenerateForControllersAsync with SchemaType = SchemaType.OpenApi3.
Is it supported in nSwag for .Net 4.5? If not, is there any other tool or solution without upgrading to .Net core?
The code I tried with nSwag:
var settings = new WebApiToSwaggerGeneratorSettings
{
DefaultUrlTemplate = "api/{controller}/{action}/{id}"
};
var jsonSettings = new JsonSchemaGeneratorSettings();
jsonSettings.SchemaType = SchemaType.OpenApi3;
var schemaGen = new SwaggerJsonSchemaGenerator(jsonSettings);
var generator = new WebApiToSwaggerGenerator(settings, schemaGen);
var document = Task.Run(async () => await generator.GenerateForControllersAsync(controllers))
.GetAwaiter().GetResult();
var x= document.ToJson();
Thanks
Related
I am following a tutorial from microsoft docs and I have created an api with Microsoft Identity Platform using Azure AD in asp.net core 5.
The tutorialI followed shows how to call an api from asp.net core 5, and I have done that part but now I want to call the api from asp.net 4.7.2. Since I am new to apis and example I am finding are not using Microsoft Identity platform to call an api secured by microsoft identity
Can someone point me to document, tutorial, or code which shows me how I can call the api. Code should be written in asp.net not core.
I have done some part but stuck on calling the api.
See the below code
Api methods:
I have already setup the api and web app in Azure portal and configured permission to 2 of the scope.
Method in api.
GetCategory()
GetCatalog()
private async Task OnAuthorizationCodeReceivedAsync(AuthorizationCodeReceivedNotification
notification)
{
notification.HandleCodeRedemption();
var idClient = ConfidentialClientApplicationBuilder.Create(clientId)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.WithAuthority(authority)
.Build();
var signedInUser = new ClaimsPrincipal(notification.AuthenticationTicket.Identity);
try
{
var apiScope = "catalog.Read, Category.Read";
string[] scopes = apiScope.Split(' ');
var result = await idClient.AcquireTokenByAuthorizationCode(
scopes, notification.Code).ExecuteAsync();
//rest of the code to call the api for both scope
// and if i have to do add some code to controller
Not sure if you are still looking for an answer but here it goes.
Once you get the accessToken with required scope, you just need to add it as Authorization Header when you make a call to the API:
const string Scheme = "Bearer";
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, url);
httpRequestMessage.Headers.Authorization = new AuthenticationHeaderValue(Scheme, result.AccessToken);
var result = await httpClient.SendAsync(httpRequestMessage)
After updating my .net core 2.1 project to .net-5 and swagger swashbuckle from 2 to 5.6.3 the swagger response examples are not getting displayed anymore. Is there a new best practice way on how to solve this problem?
On 2.1 i have added some definitions on top of my controller.
[SwaggerResponse(409, Type = typeof(IEnumerable<ErrorObjects>))]
[SwaggerResponseExample(409, typeof(MethodResponseErrors))]
And in addition to this i implemented the MethodResponseErrors like this:
public class MethodResponseErrors : IExamplesProvider<List<ErrorObjects>>
{
List<ErrorObjects> IExamplesProvider<List<ErrorObjects>>.GetExamples()
{
return new List<ErrorObjects>
{
new Error1(),
new Error2(),
new Error3()
};
}
}
After this my response examples got displayed.
I'm trying to port a asp.net mvc 3.0 to Asp.Net Core 3.0 but now I'm stuck and Cannot find UrlHelper.GenerateUrl in .Net Core 3.0. even the UrlHelper in Microsoft.AspNetCore.Mvc.Routing doesn't have GenerateUrl, seems like it is removed in .Net Core version 3.0. are there any replacements?
You can use the LinkGenerator. From the documentation:
URL generation is based on addresses, which support arbitrary
extensibility:
The Link Generator API (LinkGenerator) can be resolved anywhere using dependency injection (DI) to generate URLs.
Where the Link Generator API isn't available via DI, IUrlHelper offers methods to build URLs.
DI example:
public class MyController : Controller
{
private readonly LinkGenerator _linkGenerator;
public MyController(LinkGenerator linkGenerator)
{
_linkGenerator = linkGenerator;
}
public IActionResult Index()
{
var url = _linkGenerator.GetPathByAction(nameof(Index), "My", new { someParameter });
// ...
}
}
I need to return result in jsonp format while I'm using asp.net MVC Core.
In asp.net MVC we can use MVC.jsonp dll an it's work fine but what is the alternative in MVC Core because I can't find any.
public JsonpResult FunctionalitesTblList()
{
var settings = new JsonSerializerSettings();
return Jsonp(Rows, settings);
}
There was no built in ability to handle JSONP with MVC, so you were always using a third-party addition. Apparently, that library is incompatible with .NET Core. Therefore, your option is to find a similar library that is compatible or choose some other approach.
#CuongLe is correct that CORS is a better approach overall, so you should definitely investigate that. However, if you insist on JSONP, it's so simple to implement manually, you don't really need a library.
Simply, all JSONP is a is JSON passed into a "callback" function, specified by the client. In other words, if the callack was specified as "mycallback", the response should just look like:
mycallback({ "foo": "bar" });
As a result, your code simply becomes:
string json = null;
using (var ms = new MemoryStream())
{
var serializer = new DataContractJsonSerializer(typeof(Foo));
serializer.WriteObject(ms, foo);
json = Encoding.UTF8.GetString(ms.ToArray());
}
var jsonp = String.Format("{0}({1});", callback, json);
Response.ContentType = "application/javascript";
return Content(jsonp);
I am writing an ASP.Net 5, MVC 6 application (also referred to as 'ASP.net vNext') with Visual Studio 2015 RC.
How do I perform a simple GET request to a REST API? In .net 4.5 I would have used HttpClient but that no longer seems to be available.
I have tried adding both the 'System.Net.Http' and 'Microsoft.Net.Http' packages as advised by Visual Studio, however I still get "The type or namespace name 'HttpClient' could not be found" which leads me to believe that HttpClient is not the right way to do this in ASP.net 5?
Can anyone advise on the correct way to make HTTP GET requests in ASP.net 5?
Update: My question is not a duplicate of 'HttpClient in ASP.NET 5.0 not found?' bercause the answer given is out of date and not applicable to the latest version of ASP.net 5.0
Here is a solution for you, I just tried it out on the ASP.Net 5 Web site project template. Add the following method to HomeController
static async Task<string> DownloadPageAsync()
{
string page = "http://en.wikipedia.org/";
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
return result.Substring(0, 50);
}
}
Then in the HomeControllers Index method
string test = DownloadPageAsync().Result;
And in project.json I added the following reference at dependencies
"Microsoft.Net.Http": "2.2.22"
I found an answer which was in part from a post called '
HttpClient in ASP.NET 5.0 not found?', but there were some missing gaps because the technology has moved on a bit now. I have blogged the full solution here: http://blogs.msdn.com/b/martinkearn/archive/2015/06/17/using-httpclient-with-asp-net-5-0.aspx