Not able to resolve HttpResponseException in .Net 5 Web Api - asp.net-mvc

I am creating an Web Api using .Net Core 5. I want to implement error handling and return the response with the error. I found a article from Microsoft which suggested the following code. When I am implementing that code "HttpResponseException" is not found and I get a suggestion to install the nuget package for Microsoft.Aspnet.WebApi.Core. Once install it conflicting with the existing nuget package. I got this message "Microsoft.AspNet.WebApi.Core 5.2.8 was restored using .netFramework, Version=4.6.1..." As I said, I am trying to handling error as per best practices and my finding was to use Microsoft documentation in which it mentioned to use HttpResponseException (applicable scenario). If HttpResponseException is obsolete for .Net 5 what other option we have? Basically in the response when error occured, I want to send the customize ReasonPhrase.
public Product GetProduct(int id)
{
Product item = repository.Get(id);
if (item == null)
{
var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("No product with ID = {0}", id)),
ReasonPhrase = "Product ID Not Found"
};
throw new HttpResponseException(resp);
}
return item;
}

Related

Microsoft-Graph SDK for .NET is not returning odata.nextLink after upgrading from v1.19 to latest

When I make a request to Graph API I get in the response the "#odata.nextLink", if I use .NET SDK v1.19 I still get the value in the AdditionalData and there is also a NextPageRequest property which has an instance to make a request to the next page. But after upgrading to the latest version 4.53, using the same query I get the response with the NextPageRequest instance but not the "#odata.nextLink" in the AdditionalData.
I took a look at the release notes and there is nothing mentioning this change.
I could take the info from the NextPageRequest but I would like to understand what is actually happening here.
I found the official document to recommend using PageIterator for Paging, so I checked the source code for different version and I think this can answer your question in some terms. I mean this is recommended by Microsoft and the way it used to get next page value should explain something....
And this is what I found in SDK version
dynamic page = _currentPage;
// There are more pages ready to be paged.
if (page.NextPageRequest != null)
{
Nextlink = page.NextPageRequest.GetHttpRequestMessage().RequestUri.AbsoluteUri;
return true;
}
And this is what I see in V1.19
if (_currentPage.AdditionalData.TryGetValue("#odata.nextLink", out var value))
{
Nextlink = value as string;
return true;
}
I found the reason for this issue, commit: https://github.com/microsoftgraph/msgraph-sdk-dotnet/commit/834549348081869cc4b97d9ead6dbbf12a516264?diff=split class GraphServiceUsersCollectionResponse
[JsonPropertyName("#odata.nextLink")]
public string NextLink { get; set; }
The addition of the above property removed the odata.nextLink from the AdditionalData dictionary. This is an old commit, I'm not sure why this has not been reported as a breaking change.
I'm going to open a ticket directly to the project.

Swagger Response Examples .Net 5 are not displayed

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.

How do i solve '"Reference to type 'BaseControlContext" claim.....' for AspNet.Security.OpenIdConnect.Server

I am facing weird issue.
I am reading and creating OpenID Connect server with ASOS this article ASOS - AspNet.Security.OpenIdConnect.Server.
I simply created new sample solution and added new subclass AuthorizationProvider class of OpenIdConnectServerProvider and override the virtual method i.e. ExtractAuthorizationRequest
AuthorizationProvider.cs
public class AuthorizationProvider : OpenIdConnectServerProvider
{
public override Task ExtractAuthorizationRequest(ExtractAuthorizationRequestContext context)
{
// If a request_id parameter can be found in the authorization request,
// restore the complete authorization request stored in the user session.
if (!string.IsNullOrEmpty(context.Request.RequestId))
{
var payload = context.HttpContext.Session.Get(context.Request.RequestId);
if (payload == null)
{
context.Reject(
error: OpenIdConnectConstants.Errors.InvalidRequest,
description: "Invalid request: timeout expired.");
return Task.FromResult(0);
}
// Restore the authorization request parameters from the serialized payload.
using (var reader = new BsonReader(new MemoryStream(payload)))
{
foreach (var parameter in JObject.Load(reader))
{
// Avoid overriding the current request parameters.
if (context.Request.HasParameter(parameter.Key))
{
continue;
}
context.Request.SetParameter(parameter.Key, parameter.Value);
}
}
}
return Task.FromResult(0);
}
}
Issue:
As soon as i add Microsoft.AspNetCore.Identity (2.0.0) NuGet package to my project, context.Reject start giving the following error
"Reference to type 'BaseControlContext" claim it is defined in
Microsoft.AspNetCore.Authentication, but it could not be found.
But as soon as I remove Microsoft.AspNetCore.Identity NuGet dependency, the error goes away and all looks fine.
Note:
I am using VS 2017.
I am using dotnetcore 2.0 SDK.
I created solution using .Net Core 2.0.
Massive changes have been introduced in ASP.NET Core 2.0's authentication stack. The changes are so important that all the authentication middleware written for ASP.NET Core 1.x are not compatible (which includes all the aspnet-contrib projects).
You can read https://github.com/aspnet/Announcements/issues/262 for more information.
The good news is that we have an ASP.NET Core 2.0 RTM-compatible version of ASOS. You can find the 2.0.0-preview1-* bits on the aspnet-contrib MyGet feed (https://www.myget.org/F/aspnet-contrib/api/v3/index.json).

Error creating task using Asana API

we have been using the ASANA API about 4 month, but today we started get an error trying to create task in Asana:
5:15:48,208 ERROR [stderr] (pool-13-thread-1) Exception in thread "pool-13-thread-1" com.sun.jersey.api.client.ClientHandlerException: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "num_hearts" (Class net.joelinn.asana.tasks.Task), not marked as ignorable
05:15:48,210 ERROR [stderr] (pool-13-thread-1) at [Source: sun.net.www.protocol.http.HttpURLConnection$HttpInputStream#6eae04be; line: 1, column: 296] (through reference chain: net.joelinn.asana.tasks.Task["num_hearts"])
the error happens on client.createTask() call, see the code below:
protected void createProjectTasks(Project template, AsanaDetails asanaDetails, Long createdProjectId) {
try {
String asanaWorkspaceName = asanaDetails.getWorkspaceName();
Asana asana = new Asana(asanaDetails.getApiKey());
Tasks tasks = asana.projects().getTasks(template.id);
Workspace workspace = getWorkspace(asana, asanaWorkspaceName);
if (workspace == null) {
throw new AsanaException("Asana workspace with name " + asanaWorkspaceName + " is not found");
}
if (tasks == null) {
return;
}
Collections.reverse(tasks);
TasksClient client = asana.tasks();
for (Task task : tasks) {
TaskRequestBuilder taskRequestBuilder = new TaskRequestBuilder();
if (StringUtils.isNotBlank(task.name)) {
taskRequestBuilder.name(task.name);
taskRequestBuilder.completed(false);
taskRequestBuilder.addProject(createdProjectId);
taskRequestBuilder.workspace(workspace.id);
client.createTask(taskRequestBuilder);
}
}
} catch (ApiException e) {
throw new AsanaException(e.getMessage());
}
}
I checked the Task class, the are no field there annotated with "num_hearts", so, I'm a bit confused what got broken here, we haven't made any code changes for about a month...
and here is the api version:
<dependency>
<groupId>net.joelinn</groupId>
<artifactId>asana</artifactId>
<version>0.5.4</version>
</dependency>
Any thoughts?
Thanks in advance
We're happy to have released support in the API for hearts in both tasks and stories. These include the new fields, "hearted", "hearts", and "num_hearts". You can read more about this in our documentation.
Unfortunately, your client threw an error because it reached a new field (num_hearts) which it did not recognize. Since the client appears to be open source, you might want to send them a pull request to add support for the new hearts attributes. Alternatively, it may be worth to generalize the client so it does not throw an error when we add new fields in the future. In order to keep the API up-to-date with product developments, we will from time to time add fields and endpoints. You can rely on existing fields not going away, but it's bad to rely on no new fields being added.

How can I return IQueyrable DTO from Webapi Get so I can use Odata filters

I'm trying to use a Odata filters with ODP.net with Entity framework inside of web api project ASP.NET MVC 4.0 RC. I want to return an IQueryable of OwnDTO . I get an internal 500 error without any details. I know there is an error generation bug with webapi RC, but I dont think that bug is my issue.
Get http://localhost:51744/api/Owner called using Fiddler
[Queryable]
public IQueryable<OwnDTO> Get()
{
using (Entities context = new Entities())
{
var query = from item in context.Owners
select
new OwnDTO
{
Name = item.Name
};
return query.AsQueryable();
}
}
//very simple for example
public class OwnDTO
{
public string Name;
}
I do not want to have use my Oracle EF generated classes (DAO) to return from my Get, but I know I can if I replace EntityObject with a more friendly interface. If I return IEnumerable it works, but I want Odata filters.
Update incase someone wants a working example.. Automapper or simliar should be used in the linq and the context should injected.
[Queryable]
public IQueryable<OwnDTO> Get()
{
{
var query = from item in Hack._EFContext.Owners
select
new OwnDTO
{
Name = item.Name
};
return query.AsQueryable();
}
}
That works fine, but it looks like Odata is removed post RC. So I need to search down another path.
It does work in RC but perhaps not in RTM when it ships - not quite clear yet.
Your problem is that you are disposing your context since you are using a using block. So context get disposed before the data is retrieved.
So instead of using register your object for disposal at the end of request. Tugberk has a post here.

Resources