What is restful web service ? What are the difference between soap service and restful service ?
What is restful web service ? What are the difference between soap service and restful service ?
Modifying Swagger Schema For Web API JSON String Containing Extended Objects
Suppose I want my web API to return a JSON string which contains child objects inside of a parent object. How would setup that type of schema so that Swagger will show a Sample Value where not only the parent object shows up but child objects show up as well
I am able to copy the json file generated by Swagger but I do not know how to modify it to display what I want. Also I don't know how I would get Swagger to use my json file.
Login and fetch data
Hi,
I want to develop back end system in asp.net WEB API and front end with JQuery + bootstrap
- How to check the username and password send by ajax service is valid and allow access to home page
- how to create custom roles for example Manager,Engineer and user
- how can i know the request from the external page is belongs to which type of user ( Manager, Engineer or User), i need to show the data based on roles
- where can i get the anti-forgery token to use with external client?
how to upload file and save data with angular JS and Web API with save button.
I want to save some data from 4 parameters in the database together with the file path and upload the file in the directory with save button .
I want to do it with web API and Angular JS.
Can anyone please share the useful tutorial. So I can learn how to do it.
[HttpGet("{id}", Name = "GetTodo")]
What does the highlighted line accomplish below?
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using TodoApi.Models;
using System.Linq;
namespace TodoApi.Controllers
{
[Route("api/todo")]
public class TodoController : Controller
{
private readonly TodoContext _context;
public TodoController(TodoContext context)
{
_context = context;
if (_context.TodoItems.Count() == 0)
{
_context.TodoItems.Add(new TodoItem { Name = "Item1" });
_context.SaveChanges();
}
}
[HttpGet]
public IEnumerable<TodoItem> GetAll()
{
return _context.TodoItems.ToList();
}
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
[HttpGet("{id}", Name = "GetTodo")]
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public IActionResult GetById(long id)
{
var item = _context.TodoItems.FirstOrDefault(t => t.Id == id);
if (item == null)
{
return NotFound();
}
return new ObjectResult(item);
}
}
}
Deploying WebAPI
Is there a good tutorial someone can recommend for (non Azure) deployment of WebAPI?
update put method in web api Giving Exception
I am getting an exception with web api while trying to update data in the database.
HTTP/1.1 501 Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded
I have two tables products and categories . I am trying to update the records of Products table through put method using fiddler. i am changed the ProductName from Pizza to burger to check updat4e method and i am getting exceptiion shown above
{"ProductName":"burger","ProductDescription":"Good Pizza","ProductImage":null,"ProductRegularPrice":30.00,
"ProductDiscountedPrice":23.00,"IsErased":false,"ModifiedTime":"2017-01-01T00:00:00","CreatedTime":"2017-02-01T00:00:00","CategoryId":1}
Here is the code for my put method.
public HttpResponseMessage Put(int id, Product pro) { if (ModelState.IsValid) { db.Entry(pro).State = EntityState.Modified; db.SaveChanges(); return Request.CreateResponse(HttpStatusCode.OK, pro); } else { //return BadRequest(ModelState); return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } }
Is the exception due to foriegn key categoryid..
After publish error in api call
Hello,
i published my website. The site self is rendered, the database is build. but i can't get access to my api. the firewall is down. i get with postman only one "404 not found".
Have someone one idea to find out the problem?
Receive a File and a list of key:value in the same HTTP POST request
I need to catch a collections of files and somethings more together in the same HTTP POST request
I have a controller ASP.NET MVC Core Web Api like this :
[HttpPost] public IActionResult Upload(IFormFileCollection files, Dictionary<string, object> tags) { // whatever code ...... }
I know how do I get a collections of file with IFormFileCollection, but when I need to get both IFormFileCollection and somethings more like a IEnumerable of "key:value" pair like the code above, I get stuck.
I'm using the tool POSTMAN but i don't know how to create a request that work with my controller. I am not obligated to use POSTMAN, it's just the one I know.
Passing multiple parameters to a WebAPI controller
My code is evolving... I now want to have the products controller do the work of appending a row consisting of an Id, a Name, a Category and a Price to the products array for
the 4 parameters of ID, Name, Category and Price. These 4 parameters will be obtained from the txtid, txtName,
txtCategory and txtPrice textboxes and will be passed to the controller by "/products/appendRow". What changes do I need to make to the RouteConfig.cs file and the other files to accomplish this so that on the click of the ButtonTest, the row is added to the array?
+++++++++++++++++++++++++ RouteConfig.cs ++++++++++++++++++++++++++++++++++++++++++++++
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace WebAPI_SPA5
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
++++++++++++++++++++++++++++++++++++++ ProductsControlller.cs +++++++++++++++++++++++
namespace WebForms
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
public class ProductsController : ApiController
{
Product[] products = new Product[]
{
new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
};
public IEnumerable<Product> GetAllProducts()
{
return products;
}
public Product GetProductById(int id)
{
var product = products.FirstOrDefault((p) => p.Id == id);
if (product == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return product;
}
public IEnumerable<Product> GetProductsByCategory(string category)
{
return products.Where(
(p) => string.Equals(p.Category, category,
StringComparison.OrdinalIgnoreCase));
}
[Route("api/products/appendRow/paramId/paramName/paramCategory/paramPrice")]
public string Get(int paramId, string paramName, string paramCategory, decimal paramPrice)
{
products[paramId] = new Product ???????? what goes here ????????????????
return;
}
}
+++++++++++++++++++++++++++++++++++ default.aspx.cs ++++++++++++++++++++++++
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebAPI_SPA5
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonTest_Click(object sender, EventArgs e)
{
++++++++++++++++++ what goes here? +++++++++++++++++
}
}
}
++++++++++++++++++++++++++++ default.aspx +++++++++++++++++++++++
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebAPI_SPA5.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
getProducts();
//$("#ButtonTest").on("click", function () {
// appendItem();
return false;
//});
});
var products = ""; //global variable products
function getProducts() {
$.getJSON("api/products",
function (data) {
$('#products').empty(); // Clear the table body.
//Assign the return value to products variable
products = data;
// Loop through the list of products.
$.each(data, function (key, val) {
// Add a table row for the product.
var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
$('<tr/>', { html: row }) // Append the name.
.appendTo($('#products'));
});
});
};
function appendItem() {
var obj = products;
obj.push({ "Id": "4", "Name": "Goya Guava Drink", "Category": "Beverages", "Price": "1.50" });
//if you want to display the change in table then you need to repopulate the table here
$('#products').empty();
// Loop through the list of products.
$.each(obj, function (key, val) {
// Add a table row for the product.
var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
$('<tr/>', { html: row }) // Append the name.
.appendTo($('#products'));
});
return false;
};
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Products</h2>
<table>
<thead>
<tr><th>Name</th><th>Price</th></tr>
</thead>
<tbody id="products">
</tbody>
</table>
Id:
<asp:TextBox runat= "server" id="txtId"></asp:TextBox>
Name:
<asp:TextBox runat= "server" id="txtName"></asp:TextBox>
Category:
<asp:TextBox runat= "server" id="txtCategory"></asp:TextBox>
Price:
<asp:TextBox runat= "server" id="txtPrice"></asp:TextBox> </div>
<p>
<asp:Button runat ="server" ID="ButtonTest" Text="Append Row" OnClick="ButtonTest_Click" />
</p>
</form>
</body>
</html>
Hiding viewmodel parameters based on the controller action
I would like to hide some of my viewmodel properties based on the Verb used, because I don't want to create different viewmodels for each action.
For example if its for post, I would like like to allow them to Ignore the Id, but for put the Id can exist.
I'm using the FromBody attribute to bind my parameters.
So is it possible to make the property nullable for specific action?
How Can I Create A Custom Swagger Schema Using Swashbuckle
I have looked at several posts on using Swagger IExamplesProvider to create a custom schema but it doesn't look like it can solve my problem of creating polymorphic objects. Also Swagger2.0 appears to have limitations on displaying polymorphic objects in the Model and Example Values.
Someone mentioned in a post that this limitation was put in place intentionally by the creator of Swagger. If that is the case then why do polymorphic objects display correctly in my response body? The following are classes in my web api:
public class Company { public string Name;
public string CEO; public List<BranchInfo> Branches; public string Contact; }
public class BranchInfo
{
public string Headquarter {get; set;}
public string Country {get; set;}
}
public class CaliBranchInfo:BranchInfo
{
public string Name{get; set;}
public string Manager {get; set;}
public string ContactInfo {get; set;}
}
public class NYBranchInfo:BranchInfo
{
public string Name{get; set;}
public string Manager {get; set;}
public string ContactInfo {get; set;}
}
I would like my JSON to display all the objects in my web api including the subclasses like the following:
"Company":{"Name" : "Company Name",
"CEO" : "CEO Name","Branches" : {
"Headquarter" : "HQ Name",
"Country" : "Country Name",
"CaliBranch" : {"Name" : "California Branch", "Manager" : "Mary Sue", "Contact" : "Contact Info"}
"NYBranch" : {"Name" : "New York Branch", "Manager" : "Joe Bloe", "Contact" : "Contact Info"}
},"Contact" : "Contact Info" }
Currently in the Branches object of my JSON, the CaliBranchInfo and NYBranchInfo objects are not being displayed in the Model and Example Values.
Is it possible to use IExamplesProvider to create a schema that will produce the above JSON string in the Example Values and Model without adding CaliBranchInfo and NYBranchInfo objects as properties of the BranchInfo object and without modifying any existing objects?
c# HttpClient PostAsync with async and await not working
Hello,
I am running into a dead lock situation when trying to post to WebApi 2 from WebApi 1 using httpclient PostAsync using async and await.
Below is my **WebAPI** 1
public HttpResponseMessage Get([FromUri]int oid)
{
var orderdetails = _orderServices.GetOrderDetails(oid);
var xml = new XmlMediaTypeFormatter();
xml.UseXmlSerializer = true;
string orderdetailsser = Serialize(xml, orderdetails);
var result = PostXml(orderdetailsser);
return Request.CreateResponse(HttpStatusCode.OK);
}
public static async Task<HttpResponseMessage> PostXml(string str)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:58285/");
var content = new StringContent(str);
var response = await client.PostAsync("api/default/ReceiveXml", content).ConfigureAwait(false);
return response;
}
}
WebApi2:
[System.Web.Http.HttpPost]
public HttpResponseMessage ReceiveXml(HttpRequestMessage request)
{
var xmlDoc = new XmlDocument();
xmlDoc.Load(request.Content.ReadAsStreamAsync().Result);
xmlDoc.Save(@"C:\xmlfiles\xml2.xml");
XmlSerializer deserializer = new XmlSerializer(typeof(OrderInfoModel));
TextReader reader = new StreamReader(@"C:\xmlfiles\xml2.xml");
object obj = deserializer.Deserialize(reader);
OrderInfoModel orderdetails = (OrderInfoModel)obj;
reader.Close();
var patient_id = _patientServices.ProcessPatient(orderdetails.Patient, orderdetails.OrderInfo);
var orderid = _orderServices.ProcessOrder(orderdetails.Patient, orderdetails.OrderInfo, patient_id);
if (orderdetails.OrderNotes != null && orderdetails.OrderNotes.Count() > 0)
{
var success = _orderServices.ProcessOrderNotes(orderid, orderdetails.OrderNotes);
}
var prvid = _orderServices.ProcessOrderProvider(orderid, orderdetails.ReferringProvider);
var shpngid = _orderServices.ProcessOrderShipping(orderid, orderdetails.ShippingInfo);
var payerid = _orderServices.ProcessOrderPayer(orderid, orderdetails.Insurances);
return Request.CreateResponse(HttpStatusCode.OK, orderid);
}
I am not getting any response back to WebAPI 1 from WebAPI 2. I have gone through couple of articles online about deadlock situation. I am unable to resolve the dead lock in my case. What am I doing wrong here? Am I using the async and await properly?
What is the best practice in handling error responses in ASP Core 2 Web API?
I have been reading a lot about means and ways of relaying responses from server to client, among these methods, i.e400
, we can either do,
return BadRequest(
Modeltate);
or
return StatusCode(400, ModelState);
Which one is considered more proper for a web API? in the following example I just want to show the error handling needed some more work to extract the error from response
I will provide and example based on login controller and handling response in Angular app,
web API
controller,
[HttpPost] [AllowAnonymous] public async Task<IActionResult> Login([FromBody] CredentialsViewModel credentials) { await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); var accessToken = new AccessTokenViewModel(); if (!ModelState.IsValid) { return BadRequest(ModelState); }; if (RegexUtilities.IsValidEmail(credentials.UniqueId)) { var user = await this._usersService.FindUserByEmailAsync(credentials.UniqueId); if (StaticHandlers.IsNullObject(user)) { credentials.UniqueId = Guid.NewGuid().ToString(); // count as wrong entry and initiate lock down } else { credentials.UniqueId = user.UserName; } } var result = await signInManager.PasswordSignInAsync(credentials.UniqueId, credentials.Password, credentials.RememberMe, lockoutOnFailure: true); if (result.Succeeded) { var userToVerify = await userManager.FindByNameAsync(credentials.UniqueId); (accessToken.AuthToken, accessToken.TokenId) = await _tokenStoreService.CreateJwtTokens(userToVerify).ConfigureAwait(false); logger.LogInformation( credentials.UniqueId + " logged in."); return Ok(accessToken); } else { ModelState.AddModelError("Invalid Credentials", "Invalid credentials, please try again!"); return BadRequest(ModelState); logger.LogCritical("Invalid Credentials"); // return StatusCode(400, "ModelState"); =======> this response handling on the client side is different from the method shown below return BadRequest(ModelState); } }
And in my front end
errors: string[] = []; login() { if (this.loginForm.valid) { this.userService.login(this.loginForm.value) .subscribe((response) => { console.log(response); this.store.dispatch(new authActions.Signin); this.store.dispatch(new authActions.SetToken(response['authToken'])); if (response['authToken']) { localStorage.setItem('token', response['authToken']); this.router.navigate(['/dbapp']); } }, (error) => { this.errors = (this.modelStateHandler.ErrorResponseHandler(error)); }) } } public ErrorResponseHandler(error: string[]) { let modelStateErrorArray: Array<Array<string>>; let errorArray:string[] = []; console.log(error); if (error){ if (error['status'] == '400') { modelStateErrorArray = error['error']; var errorKeys:string[] = Object.keys((modelStateErrorArray)); for (let errorKey of errorKeys) { let errorMsg: string= (modelStateErrorArray[errorKey][0]); errorArray.push(errorMsg); } console.log(errorArray); return errorArray; } } }
HTML component
<div *ngIf="errors" class="alert alert-danger" role="alert"><strong>Oops!</strong><div *ngFor="let error of errors"> {{error}}</div></div>
How to create Store Procedure in ASP.NET Web Application?
Hi everybody!
- How to create Store Procedure in ASP.NET Web Application? (My project has deploy on IIS)
- How to call Store Procedure from app. Ex: call from UWP app
Thank you!
SocketException: No connection could be made because the target machine actively refused (ipaddress)
When I execute the following code to get the token, I got the error "SocketException: No connection could be made because the target machine actively refused (ipaddress)". What caused the error? Did I miss something? Thanks.
using (var client = new HttpClient()) { client.BaseAddress = new Uri("http://localhost:1234"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var body = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("grant_type", "password"), new KeyValuePair<string, string>("client_id", "client_id"), new KeyValuePair<string, string>("client_screte", "client_screte"), new KeyValuePair<string, string>("username", "xyz"), new KeyValuePair<string, string>("password", "Password"), new KeyValuePair<string, string>("scope", "scope"), }; var content = new FormUrlEncodedContent(body); HttpResponseMessage tokenResponse = await client.PostAsync("/connect/token", content); }
Debug a webapi controller in Xamarin.Forms solution
Hi,
I'm quite new to developing, trying to create my first Xamarin.Forms app. Things goes quite well, but one major issue is that I cannot debug my WebApi controllers included in the same solution as the UWP, shared project etc. The solution looks as below image
(currently disabled Android and iOS, just running UWP). The problem is that I cannot debug anything in my WebApplication controllers. All I get at my breaktpoints in the controllers is the message: The breakpoint will not currently be hit. No symbols have
been loaded for this document.
I tried to change options - debugging - symbols, but I only achieve a slow project downloading symbols for several minutes. Also enabled Enable Just my code, and Enable .Net Framework source stepping, with no success.
So, something is wrong with my solution, or I have missed something crucial regaring debugging.
BR /Magnus
Raw json returned response body with html tags
I've opened this issue with Swagger also, but please assist if you faced it before:
https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/564
I'm getting the below response with html tags like \r\n in Swagger UI:"{\r\n \"eventId\": \"6ab342c2-a06d-4595-82fb-91d9b9380f0d\",\r\n \"name\": \"string\",\r\n \"comment\": \"string\"}
When having the following attribute on my action method:[ProducesResponseType(200)] [ProducesResponseType(typeof(JsonErrorResponse), 400)]
If I remove the 400 response type, it works and returns clean formatted json.
or if I write it like[ProducesResponseType(200)] [ProducesResponseType(400)]
I'm using .net core 2.0 and SwachBackle.AspNetCore 1.0.0
How to request Web API OAuth token using HttpClient in a C# Windows application
I have an asp.net REST server that has OAuth2 token authentication added using the various available middlware. I have been successfully using it from JS clients, and test tools such as Postman.
Below are some screen shot from Postman which will succeed...
So, I just send simple for encoded grant_type, username and password,
So we have an endpoint /token
,
and I send the username/password as application/x-www-form-urlencoded
I am having a huge amount of trouble getting the same thing to work from a .net client application using the HttpClient
I have the following test code...
public async void Test() { HttpClient client = CreateHttpClient(); //string body = "grant_type:password\nusername:peter\npassword:peter"; string body = "grant_type=password&username=peter&password=peter"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "/token"); request.Content = new StringContent(body, Encoding.UTF8,"application/x-www-form-urlencoded");//CONTENT-TYPE header var response = await client.SendAsync(request); int i = 0; // breakpoint here } private HttpClient CreateHttpClient() { HttpClientHandler handler = new HttpClientHandler() { UseDefaultCredentials = false}; HttpClient client = new HttpClient(handler); client.BaseAddress = new Uri(m_endpoint); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); return client; }
However, when i call, I always get back Bad Request, no matter what I have tried. Once again, this works fine from test tools such as Postman, and alo when I call it via web apps using JavaScript, but I just can't get it to work from my C# (console) appplication
Thanks in advance for any help!
CRUD operation using Web API Stored Procedure in SQL Server 2012 and EF 6
Hi, All of you. I am creating one application for demo purpose using WEB API 2, SQL Server 2012 and EF-6.
I want perform all CRUD operation using single Stored Procedure. When I write single Stored Procedure for Perform all CRUD operation I am unable to perform it. But if I use separate Stored Procedure for all CRUD operations am able to do this.
First of all I want to know Is it possible to perform all CRUD operations using Single Stored Procedure?
If yes, Please suggest me the way.
Thank you.