Click here to Skip to main content
15,892,839 members
Everything / WebAPI2

WebAPI2

WebAPI2

Great Reads

by Vincent Maverick Durano
This article will talk about how to implement a custom wrapper for your ASP.NET Core and Web API applications for managing exceptions, providing meaningful and consistent responses to consumers.
by kannankeril
This article is an attempt at splitting out the controller layer to reduce its complexity and improve quality and maintainability of the resulting code.
by Livio Francescucci
Use a JWTToken to access a .NET Core Web API leveraging IdentityServer4 / OAuth2.

Latest Articles

by Vincent Maverick Durano
This article will talk about how to implement a custom wrapper for your ASP.NET Core and Web API applications for managing exceptions, providing meaningful and consistent responses to consumers.
by Quí Nguyễn NT
This is a demonstration of a basic example of single page Angular application and micro-service architecture on Azure.
by Aram Tchekrekjian
How to create and deploy your first ASP.NET Core Web API on IIS
by Sunny Makode
This is an introductory article about creating an Odata Rest API in collaboration with Entity Framework. We are also going to use Autofac as our IOC container. Also, Repository and Unit of Work pattern will be used for cleaner access of persistence model through our ORM (Entity Framework).

All Articles

Sort by Updated

WebAPI2 

4 Aug 2023 by maysam_p82
No public constructor is available for type System.Security.Principal.IIdentity UnityConfig File: var container = new UnityContainer(); container.RegisterType(); container.RegisterType();...
4 Aug 2023 by OriginalGriff
Read the error message: No public constructor is available for type System.Security.Principal.IIdentity It means what it says: you cannot construct an instance of that class (or Interface, which is what I suspect it is from the name). We can't...
16 Sep 2022 by Member 15090354
I have a method like below public IHttpActionResult([FormUri] string name) { var response =_servcie.GetDetails(name); return Ok(response.Result); } The application has the JSON configuration at the config level. could you please assist...
12 Aug 2022 by Member 15090354
Hi Team, I am using Odata in our application due to that i am not able to call web api methods in Postman or web browser Could you please suggest how to create web api methods same as normal web api methods [EnableQuery] public...
1 Jul 2022 by Member 10738936
This issue comes on live server. In local IIS its working. for deserialize i am uing var data = JsonConvert.DeserializeObject(response.Content); this is my json: {"Table":[{"OrganisationID":1001,"NAME":"LORD MEHER INTER...
19 Jun 2022 by Gerardo Gamo
If you are using NET framework (any version capable of having swagger) in you web.config, 1. create a new key called IsSwaggerEnabled and set it to true ...
19 Jun 2022 by istudent
I using swashbuckle v 5.6.0 for api documentation and ui for test in asp.net web api2. I do not want give ability for the user to post data from swagger ui in production. How do I disable it? What I have tried: GlobalConfiguration.Configuration .EnableSwagger(c => ...
31 Mar 2022 by ahmed_sa
zip files not downloaded on angular 13 although zip files created and api not give error ? I work on application asp.net web api core 2.2 and angular 13 . I make web api compress files and create it first as zip files . then downloaded on my...
22 Oct 2021 by CHill60
Quote: Can you check my stored procedure once ? The answer to that question is "No. We can't" - for the reasons that OriginalGriff has given you above You also state that you "already done this". So I assume that you ... 1. put a breakpoint on...
22 Oct 2021 by Cse Engineer
I created an update stored procedure then used that stored procedure in the put method of the web api and then consumed that api in the mvc controller. Category_Id is the primary key. What I have tried: ALTER PROCEDURE [dbo].[Update] -- Add...
22 Oct 2021 by OriginalGriff
Quote: No error is coming in all above code. First i have created an updated stored procedure to update the record and then implemeted the put method in web api controller and then consumed it in the mvc controller but whenever i try to update...
25 Aug 2021 by Alexander Angelopoulos
I have a simple web api project which I am trying to call using an HttpClient (trying to fetch products from database Table). I get a result of an empty array [] although I have stored data in my Database (SQL Server). API: Model: public...
25 Aug 2021 by Richard Deeming
Quote: [ResponseType(typeof(Products))] public IQueryable GetProducts() The ResponseType value doesn't match the type you are returning. But since you're returning a concrete type, rather than an IHttpActionResult, that attribute is...
19 Aug 2021 by Richard MacCutchan
This is the same issue as you posted yesterday at Getting error "message": "could not find file 'D:\\home\\site\\wwwroot\\PDF_report.pdf'.",[^]. Please read the solution that you were given.
17 Aug 2021 by Richard Deeming
Quote: string[] str = response.RequestMessage.RequestUri.LocalPath.Split('/'); // str contains: { ..., "PDF_Report.aspx" } ... str[str.Length - 1] = str[str.Length - 1].Replace(".aspx", ".pdf"); // str contains: { ..., "PDF_Report.pdf" } var...
17 Aug 2021 by .NET- India
Hi, I am writing following code in .NET Core Web API. And project is divided in "API", "Service", "Repository". I have following request body and it is sending a mail with an attachment with a link given in "Attachment". { "To":...
17 Jun 2021 by Manidas Payyoli
I am getting below error in testing postman.I OFF SSL also The requested resource could not be found but may be available again in the future. Subsequent requests by the client are permissible after giving this route attribute in class...
16 Jun 2021 by ahmed_sa
I work on web api asp.net core 2.2 I face issue I can't return true or false from web api compare excel as below so if excel is identical then return true else return false public bool CompareExcel(string filePath, string templatePath, out...
16 Jun 2021 by Chris Copeland
Most of the work is already done in the controller, you just need to return the correct IActionResult from the controller method. This tutorial page[^] has some good examples of what you can return, you just need to see which one applies here.
7 Dec 2020 by viprat
Hi All, We are getting clickjecking vulnerability and it suggest to use x-frame option in response header. What I have tried: we have added x-frame option DENY is response header. So it should not allows to iframe application. Now using...
7 Dec 2020 by Richard Deeming
X-Frame-Options - HTTP | MDN[^] If you can still load your page in an , then either you haven't set the header properly, or you are using a really old browser which doesn't support the header - eg: Internet Explorer 7. NB: In more...
5 Nov 2020 by OriginalGriff
You can't return byte data there: it doesn't exist, because you haven't read it. You only read any data when there is at least one row available - and there should be only one row, so the while loop is redundant, just use an if instead - and...
5 Nov 2020 by Virendra S from Bangalore, Karnataka
I am trying to fetch a image from MS SQL DB. GetEmpImg() is getting called by in other class, i want return the bytes data. but return code is not reachable my code snippet: public static byte[] GetEmpImg(int emp_no) { ...
5 Nov 2020 by Richard Deeming
Either you haven't deployed the CORS-enabled version to the server, or the API you've updated isn't the API you're calling. Use your browser's developer tools to inspect the network request, and look at the response headers to check the...
5 Nov 2020 by Virendra S from Bangalore, Karnataka
i am getting the CORS issue while accessing the deployed ASP.Net Web API 2 while running the angular app locallly. the same API is working with postman. Error: Access to XMLHttpRequest at...
2 Nov 2020 by DevCodeproject1
Using Swagger (Swashbackle Package) in the .NET framework for WEB API specifications. The Swagger UI is completely different from the .NET Core's swagger UI. Is it possible to implement the Same theme in the Swagger, If yes, Could you suggest a...
30 Oct 2020 by Richard Deeming
In your route, the parameter is called id. In your method, the parameter is called emp_no. Either change your method parameter name: public testOrg GetOrgTreeStr(int id) or pass the value in the querystring: ...
30 Oct 2020 by Virendra S from Bangalore, Karnataka
Controller: public class testADOController : ApiController { [HttpGet] public testOrg GetOrgTreeStr(int emp_no) { return testadoBL.GetTestOrg(emp_no); } } WEbAPiCOnfig.cs file data: ...
15 Sep 2020 by Sandeep Mewara
Try this: How to customize Swagger UI in ASP.NET Web API – Umamaheswaran[^] Seems he has few customized templates: GitHub - ostranme/swagger-ui-themes: A collection of css themes to spice up your Swagger docs[^] Another reference: Implementing...
23 Aug 2020 by xigmond
var respContent = await response.Content.ReadAsStringAsync(); var data = JsonConvert.DeserializeObject(respContent);
21 Aug 2020 by Codes DeCodes
I am creating prototype of application where in I am trying to send data in request header and body from C# MVC Controller and also created web api project Post action to process the request. My code goes like this:: MVC Project code to Post Request: public class HomeController :...
8 Jun 2020 by Richard Deeming
It looks like you're using the Strathweb.CacheOutput library. Looking at the documentation, the value passed to InvalidateCacheOutput needs to be the method name whose cache you want to invalidate. You don't have a method called y on the...
8 Jun 2020 by Member 14800672
Let's say i have this controller public class abController : BaseApiController { [HttpGet] [Route("api/x", Name = "x1")] [CacheOutput(ServerTimeSpan = 3600, ClientTimeSpan = 3600)] public async...
4 Jun 2020 by Vincent Maverick Durano
This article will talk about how to implement a custom wrapper for your ASP.NET Core and Web API applications for managing exceptions, providing meaningful and consistent responses to consumers.
21 May 2020 by MadMyche
I would probably start a new project, getting all of the authentication in and then migrate the code from your current application. I would recommend reading through the following links to MS Docs, and then go step by step once you understand...
21 May 2020 by Member 14800672
I created an empty web api project (without authentication) and made my controllers and Database. Now i want to make google authentication, what should i do? All the data online shows how to do google authentication if u created a project with...
26 Apr 2020 by MadMyche
You don't. Those are necessary portions of the URL to tell the browser what protocol to use (HTTPs, FTP, Gopher), the domain go to (localhost), as well as what port number (00000) to use Once it gets to localhost:0000, then it is your web...
26 Apr 2020 by Member 14800672
Here's my url https://localhost:00000/api/Details?Id=1 how to make it not start with local host https://localhost:00000 i want it to be exactly like this /api/Details?Id=1 What I have tried: Here's my register Method: public static...
22 Apr 2020 by Richard Deeming
There is no native support for multiple result sets in Entity Framework. If you're using EF6, you can get the ObjectContext and manually translate the results, as described in this SO answer[^]: using (TableDBContext context = new...
22 Apr 2020 by Member 14800672
I have a stored procedure that has input Id and Loc and returns Id,Loc and Description So i made a class in C# called RetrieveDE that has these three returned fields Then i edited my stored procedure to return two selects instead of one. And now...
8 Apr 2020 by Member 11183217
I want to get all the messages from Telegram channel and display them in an ASP.NET webpage (c#,mvc)... What I have tried: i have tried all the ways and i didn't get the reference as well can you please some one give me the reference it will...
25 Mar 2020 by Quí Nguyễn NT
This is a demonstration of a basic example of single page Angular application and micro-service architecture on Azure.
14 Feb 2020 by MadMyche
If you are using SQL Server, another option would be to utilize SQL Agent as well as Database Mail How To Send Mail Using SQL Server: Part 1[^]
14 Feb 2020 by Pascualito
Hi, Technologies : ASP.Net WebForms or MVC, WebAPI I need to create "something" to send notifications, kind of reminders, for instance to remind a person his appointment with a doctor. The dates to send the notifications are saved in a DB The...
14 Feb 2020 by Pascualito
Hi I haven't read the first option yet, but I agree with you about the second solution. It's seems to be a very simple solution. Thanks a lot Richard!! Pascualito
14 Feb 2020 by Richard Deeming
If it has to be in ASP.NET, there are various tools you can use to schedule background jobs: How to run Background Tasks in ASP.NET - Scott Hanselman[^] However, I would be inclined to create a small console application to scan the database and...
8 Feb 2020 by Aram Tchekrekjian
How to create and deploy your first ASP.NET Core Web API on IIS
2 Feb 2020 by Member 11183217
hi, I have tried the swagger ui versioning by using the .net core 3.1 with API 2.0. i have completed this scenario up to controller level. but i dont know how to do this versioning for controller Action...anyone can you please help me on this i have struggled past 3 days on this. help me...
2 Feb 2020 by RickZeeland
Maybe you can try NSwag, see: https://elanderson.net/2019/10/swagger-openapi-with-nswag-and-asp-net-core-3/[^] https://www.slant.co/topics/1397/viewpoints/20/~best-web-frameworks-to-create-a-web-rest-api~nswag[^]
28 Jan 2020 by MadMyche
Your assigned project at the business level is not always going to be the same as your programming project. The backend requirement of your assignment is to use SOA (Service Orientated Architecture). This should be a standalone project and if it were mine I would use WebAPI for this. Your...
28 Jan 2020 by Member 12775034
I have been assigned to develop a project which is supposed to be a responsive web application as well as a mobile app. The project is supposed to be developed in .NET. The main requirement is that it should be based on a service-oriented architecture. That is, any request, no matter which...
7 Jan 2020 by MadMyche
Have you looked into there GIT repository and read this issue? Disabling swagger ui · Issue #301 · domaindrivendev/Swashbuckle · GitHub[^]
11 Dec 2019 by MadMyche
Well... the problem is quite evident; many of these are various control or otherwise special characters. The %, &, #, and / should be visible to anyone who has looked at a URL as separators, fragment identifiers, routing, and escape characters. I personally would not use GET with a password, as...
11 Dec 2019 by Wiep Corbier
So I have an APIservice made that does a lot of stuff with data. One thing it does is get 'Candidates' by their Login data. Code like this does the job [HttpGet] [Route("{name}/{password}/ByNameAndPassword")] public async Task...
9 Dec 2019 by Member 10033441
Hi All, I am trying to download file but there is no content present after download.Please assist me to resolve it.Below is my code. WebApi Code ------------- [Authorize] [HttpPost] [Route("downloadStaticDocument")] public HttpResponseMessage...
8 Dec 2019 by Sunny Makode
This is an introductory article about creating an Odata Rest API in collaboration with Entity Framework. We are also going to use Autofac as our IOC container. Also, Repository and Unit of Work pattern will be used for cleaner access of persistence model through our ORM (Entity Framework).
30 Nov 2019 by Asif Rehman
This is working fine. public IHttpActionResult Post(Categories categories) { //... } But When I change Categories to Categories[] to received multiple records from javascript client, it show null object. public IHttpActionResult Post(Categories[] categories) { //... } from postman...
30 Nov 2019 by Ashutosh Gpt
create another class contains list of Categories public class CategoriesList { IList ListItem; } public IHttpActionResult Post(CategoriesList categories) { //... } body may something like this: ListItem : [ { id: 1, Category: 'Value1' }, { id: 2, Category: 'Value2' } ]
17 Oct 2019 by RickZeeland
Not sure if you are using ASP.NET but here is an interesting article: https://dzone.com/articles/use-aspnet-web-api-and-angular-to-build-a-simple-a[^]
17 Oct 2019 by L Viljoen
Hi Has anyone had experience getting angular to run off a .Net Framework Web API project similar to the way .Net Core runs SPAs using the startup.cs class. I need something that can run it similar to how the ng Serve command works when I run the project Note: this is for .net Web API and not...
15 Oct 2019 by #realJSOP
That's highly inefficient and requires a sh*t-ton of needless code. Just save the whole entity and be done with it. If your entities and DAL are properly designed, this shouldn't be an issue.
15 Oct 2019 by Vijay Radia
Hello, I have one entry form, when i click on update, i have to find only those control whose values are updated. I will then pass those values to web api to update in database using PUT http verb. Please help me how can i achieve this. Thanks What I have tried: I don't want to do any...
15 Oct 2019 by OriginalGriff
Quote: I don't want to do any server side code e.g. Textchange event etc. Good. Server side TextChanged event handling is a bad idea - it means that each keypress by the user has to make a round trip to the server and back, which is slow and wasteful. So instead, use Javascript TextChanged...
9 Sep 2019 by chandubbbb
In GPS application we receive data every 10 seconds from each device.we are displaying the device count like OffRoad, Moving, Stopped and Not working suppose no data from the device in the last 5 minutes we are marking them as Not working, we are updating device data in concurrent dictionary...
9 Sep 2019 by pkfox
Step through your code in the debugger and look at the values as you go - you say the data is identical but it it obviously isn't
8 Sep 2019 by pkfox
What does the debugger tell you ? No one will trawl through all that code for you - make more of an effort to pinpoint the problem
31 Aug 2019 by Thomas Daniels
I can't see the code you use to render the image, but I'm guessing that you create an img tag with as src the API response. D:\Images1\1.jpg is not a file path that will be recognized by your browser. You'll have to use this: file:///D:/Images1/1.jpg But note that if anyone accesses your MVC...
31 Aug 2019 by suneel kumar gupta
I have Web API that will return all image URL in Json Result. [ { "Path":"D:\\Images\\1.jpg" }, { "Path":"D:\\Images\\2.jpg" }, { "Path":"D:\\Images\\3.jpg" } ] I have hosted by above api in subdomain like- http://api.xyz.com/api/images/img1 now I want to consume this api in main...
2 Jul 2019 by Mustafa Kok
Developing a very simple Web API architecture using ASP.NET Web API2 whose operations can be extended by just adding new operation types
25 Jun 2019 by Gerry Schmitz
asp.net mvc - MVC AuthenticationManager.SignOut() is not signing out - Stack Overflow[^]
30 May 2019 by titu-1670319
Hi I am using unity container for depency injection by attributes using following code container.RegisterTypes( AllClasses.FromLoadedAssemblies() .Where(t => t.GetCustomAttributes(true).Any()), ...
30 May 2019 by Gerry Schmitz
Quote: Problem is sometimes i get following exception which goes if i clean and rebuild the solution. am i missing something ? Yes. You're missing another clean and rebuild.
30 May 2019 by Pascualito
Hello, I need to upload images using jquery $.ajax and web api controllers The Model is simple: public class Person{ [Required] public string Name {get;set;} public HttpPostedFileBase Photo{ get; set; } } The api controller is very simple too: [HttpPost] public...
30 May 2019 by MadMyche
The best way to do this would be to not build your own JSON from scratch; and to use JavaScripts FormData object to assemble the information and submit it. Thoughbot | Ridiculously simple Ajax uploads with FormData[^] SitePoint | Easier Ajax With the HTML5 FormData Interface — SitePoint[^]...
20 May 2019 by Pete O'Hanlon
There are multiple ways that you could do this. You could use the parent component to act as a coordinator, so you might have an EventEmitter in the component containing the table and then, when this is set, it raises the event which is being listened to by the parent. The parent would then...
20 May 2019 by ahmed_sa
How to pass table name from first component to second component on angular 7 when click button ? I have two components and i need to pass table name from first component to second when click button on first component As you see below in first component i write table name by hand this will...
30 Apr 2019 by phil.o
Have you seen and tried Newtonsoft: Serializing Collections[^] already? Your code is quite confusing because what you are serializing the Content property of the b variable enclosed between square brackets. Try storing this value in a variable, put a breakpoint on that line, and launch a debug...
29 Apr 2019 by Member 12919448
Hi, I got error message that I have to deserialize json, so I did: var user = db.Users.Select(x => new RegisterBindingModel() { Id = x.Id, Email = x.Email, UserName = x.UserName, FirstName = x.FirstName, ...
29 Apr 2019 by F-ES Sitecore
You have a list of RegisterBindingModel objects, you then create a new object with a property of Data that points to that list and a Total property, you then try and deserialise that object back to a list. Obviously that's not going to work as the new object isn't a list of...
28 Apr 2019 by Member 12919448
Hi, I used kendo.dynamic.linq.DataSourceResult to implement filtering in server side. [AcceptVerbs("GET","POST")] public DataSourceResult Filter(Models.DataSourceRequest request) { if (request != null) { request.Filter.Field =...
5 Apr 2019 by sid2586
I have existing logic to validate against database in place.For eg. I have two controllers, ControllerA & ControllerB, i have AuthorizeAttribute on ControllerA, Now when i get request for ControllerA action method, first my Custom AuthorizeAttribute get request it process some authorization...
5 Apr 2019 by David_Wimbley
Rather than trying to fit a square peg through a round hole, you need to refactor your code to something that will actually work and make sense. Calling controller code from an attribute doesn't make sense. Pull the IsValidUser method out of the Controller B, move it to a class called...
2 Apr 2019 by Bohdan Stupak
No need to construct a new object with HttpRequestMessage re = new HttpRequestMessage(); use static Request instead Request.Headers.TryGetValue("username", out var test);
22 Mar 2019 by ahmed_sa
problem get error when make service getallemployee Conversion of type 'Promise' to type 'Employee[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.ts(2352) Conversion of type 'Promise'...
22 Mar 2019 by Bohdan Stupak
The error is pretty self-descriptive. this.http.get returns Promise which you unsuccesfully try to convert into your entities. Use this.http .get('https://localhost:44326/api/Employee') .then(res => //your logic)
21 Mar 2019 by Richard Deeming
You're returning an array containing the value of every column from every row, flattened out into a single list. You need to return an array of objects instead: while (reader.Read()) { columnNames.Add(new { rownum = (Int64)reader["rownum"], code = (Int32)reader["code"], ...
21 Mar 2019 by ahmed_sa
problem data display on strange format How to convert it to json format I make function return list of object data of column name where pass table name meaning function return column names joined with table reference but problem data display in strange format as below : the result as...
16 Mar 2019 by ahmed_sa
I work on project angular 7 with asp.net web API core 2.1 data display on reference.component.ts ngoninit event variables this.RefListVal but not show on Reference.component.html my web API function [HttpGet("{tableName}")] public List GetColumnNames([FromRoute] string...
9 Mar 2019 by sharadverma_VNS
I have successfully created ASP.NET WEB API 2 project with OAuth security token and it is working fine but there is one issue with this. When I copied the security token generated by this API for an authenticated user by providing correct user id and password, after that using it (same copied...
5 Mar 2019 by Richard Deeming
That method is defined in the System.Net.Http.Formatting assembly, which is distributed via NuGet. Confusingly, the NuGet package name is Microsoft.AspNet.WebApi.Client: NuGet Gallery | Microsoft.AspNet.WebApi.Client 5.2.7[^] NB: The async conversion of your method should not call .Result at...
5 Mar 2019 by Codes DeCodes
In my project, I am calling webapi services - Get action from controller of another project. My code is: using System.Net.Http; using System.Configuration; using System.Net.Http.Headers; public ActionResult Index() { ViewBag.Place = new SelectList(GetPlaces(), "ID",...
1 Mar 2019 by ahmed_sa
problem How to assign ng model input type text on header to ngfor element ? I work on application work on angular 7 with asp.net core 2.1 on html component i have input type text and i need to assign it to ngfor element ? but cannot do that actually i need when user write or input type textbox...
27 Feb 2019 by Bohdan Stupak
It's hard to figure out something without a snippet of a client code calling your controller. But the most common reason is that the shape of a data you POST from a client mismatches what you expect on a server. Please double check this.
27 Feb 2019 by kia9372
i create aweb service in asp core2.2 and send data from client (angular6). my controller in Admin area . this Startup : public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { ...
27 Feb 2019 by ahmed_sa
Problem How to return EmployeeCode on angular employees component.html ? Sample data ReferenceTable Code tableName FieldName LabelText 111 Employees EmployeeId EmployeeCode Result of calling GetLabelTextForEmployee('Employees','EmployeeId') it suppose Return EmployeeCode I work...
27 Feb 2019 by StijnBollen
In your employees.component.ts file you import OnInit and OnDestoy and implement them. On your class, you'll need a employeeCode string-property to store the value. In ngOnInit you need to subscribe to the ApiService's GetLabelText with the needed parameters and in ngOnDestroy you'll need to...
22 Feb 2019 by Afzaal Ahmad Zeeshan
Your question itself has the answer, your task has not yet been evaluated—Result = "{Not yet computed}. You need to give it more time, and check the result later. This time won't be known to you, since it is undefined amount of time. That is because in the synchronous code you need to wait for...
22 Feb 2019 by Codes DeCodes
I am calling a web service from MVC controller to post data. Both stays in same solution. My code in Web Api is: [HttpPost] public IHttpActionResult InsertUsers([FromBody]tblUserAgentSubAgentVMWithByte tblUserAgentSubAgentVM) { return Ok("Success"); } My code of...