Web Api
405: Method not found
Web Api:
http://www.tutorialsteacher.com/webapi/web-api-tutorials
Filters:
http://www.tutorialsteacher.com/webapi/web-api-filters
6. ASP NET Web API MediaTypeFormatter
In this video we will discuss
1. What is MediaTypeFormatter
2. How to return only JSON from ASP.NET Web API Service irrespective of the Accept header value
3. How to return only XML from ASP.NET Web API Service irrespective of the Accept header value 4. How to return JSON instead of XML from ASP.NET Web API Service when a request is made from the browser
5. Point you to an article that describes how to return CSV formatted data from ASP.NET Web API
Text version of the video http://csharp-video-tutorials.blogspo...
Slides http://csharp-video-tutorials.blogspo...
All Dot Net and SQL Server Playlists https://www.youtube.com/user/kudvenka...
All ASP.NET Web API Text Articles and Slides http://csharp-video-tutorials.blogspo...
CSV Formatter http://www.tugberkugurlu.com/archive/...
7. Implementing post method in ASP NET Web API
Text version of the video http://csharp-video-tutorials.blogspo...
Slides http://csharp-video-tutorials.blogspo...
All Dot Net and SQL Server Tutorials https://www.youtube.com/user/kudvenka...
All ASP.NET Web API Text Articles and Slides http://csharp-video-tutorials.blogspo...
responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
responseMessage = Request.CreateResponse(HttpStatusCode.Created, employee);
public HttpResponseMessage Post([FromBody] EmployeeDetails employee)
{
HttpResponseMessage responseMessage = new HttpResponseMessage();
try
{
SetEmployee(0, employee);
responseMessage = Request.CreateResponse(HttpStatusCode.Created, employee);
responseMessage.Headers.Location = new Uri(Request.RequestUri + employee.id.ToString());
}
catch (Exception ex)
{
responseMessage = Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
return responseMessage;
}
8. Implementing Delete method in ASP NET Web API
9. Implementing PUT method in ASP NET Web API
10.Custom method names in ASP NET Web API
Text version of the video http://csharp-video-tutorials.blogspo...
Slides http://csharp-video-tutorials.blogspo...
All ASP.NET Web API Text Articles and Slides http://csharp-video-tutorials.blogspo...
All ASP.NET Web API Videos https://www.youtube.com/playlist?list...
All Dot Net and SQL Server Tutorials https://www.youtube.com/user/kudvenka...
It will work
public IEnumerable<EmployeeDetails> Get()
{
return employess.ToList();
}
It will work
public IEnumerable<EmployeeDetails> GetDetails()
{
return employess.ToList();
}
Will not work
public IEnumerable<EmployeeDetails> LoadDetails()
{
return employess.ToList();
}
It will work
[HttpGet]
public IEnumerable<EmployeeDetails> LoadDetails()
{
return employess.ToList();
}
HttpGet - Get
HttpPost - Post
HttpPut - Put
HttpDelete - Delete
11. ASP NET Web API query string parameters
public IEnumerable<EmployeeDetails> Get(string gender = "All")
{
return employess.Where(x => x.id == id).ToList();
}
12. FromBody and FromUri in Web API
Parameter binding
public void Put(int id, Employee value)
{
SetEmployee(value, id);
}
public void Put(int id, [FromBody] Employee value)
{
SetEmployee(value, id);
}
public void Put([FromBody]id, [FromUri] Employee value)
{
SetEmployee(value, id);
}
12 Call ASP NET Web API from jQuery
13 Calling ASP NET Web API service in a cross domain using jQuery ajax
Same origin policy
Different origins
Cross domain issues
Browser not allowed cross domain access , ways to get work around this problem.
1.json with padding ( jsonp )
2.Coross origin resource Sharing.
JSONP:
JSONP stands for Json with padding does it wraps the data in a function.
Nuget package:
webapicontrib.formatting.jsonp
P15_Cross origin resource sharing ASP NET Web API
Microsoft.
http://www.c-sharpcorner.com/article/enable-cors-in-asp-net-webapi-2/
EnableCorsAttribute cross = new EnableCorsAttribute("*", "*", "*");
//EnableCorsAttribute cross = new EnableCorsAttribute("http://local1,http://local1", "*", "GET,POST");
config.EnableCors(cross);
[EnableCorsAttribute("*", "*", "*")]
[DisableCors]
In output: If it is same domain.
Access-Control-Allow-Origin:*
In output: If it is other domain.
Access-Control-Allow-Origin:http://localhost:4523
P16_Enable SSL in Visual Studio Development Server:
using System.Web.Http.Filters;
HttpActionContext: Access both request and response object
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Found);
actionContext.Response.Content = new StringContent("use https instead of http");
UriBuilder uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
uriBuilder.Scheme = Uri.UriSchemeHttps;
uriBuilder.Port = 44357;
actionContext.Response.Headers.Location = uriBuilder.Uri;
}
else
base.OnAuthorization(actionContext);
}
}
WebApiConfig
config.Filters.Add(new RequireHttpsAttribute());
[RequireHttps]
public class EmployeeController : ApiController
{
}
P18 Implementing basic authentication in ASP NET Web API:
public class BaseAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authenticationTocken = actionContext.Request.Headers.Authorization.Parameter;
//username:password ( base64 ) pass by server
// base64 deocde
byte[] base64 = Convert.FromBase64String(authenticationTocken);
string decodedAuthenticationToken = Encoding.UTF8.GetString(base64);
string[] tokens = decodedAuthenticationToken.Split(':');
string userName = tokens[0];
string password = tokens[1];
if (new UserRepository().IsAuthenticated(new User() { UserName = userName, Password = password }))
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
}
}
//base.OnAuthorization(actionContext);
}
}
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authenticationTocken = actionContext.Request.Headers.Authorization.Parameter;
//username:password ( base64 ) pass by server
// base64 deocde
byte[] base64 = Convert.FromBase64String(authenticationTocken);
string decodedAuthenticationToken = Encoding.UTF8.GetString(base64);
string[] tokens = decodedAuthenticationToken.Split(':');
string userName = tokens[0];
string password = tokens[1];
if (new UserRepository().IsAuthenticated(new User() { UserName = userName, Password = password }))
{
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Unauthorized);
}
}
//base.OnAuthorization(actionContext);
}
}
[BaseAuthentication]
public HttpResponseMessage Get(int id)
{
HttpResponseMessage responseMessage = null;
string username = Thread.CurrentPrincipal.Identity.Name;
}
public HttpResponseMessage Get(int id)
{
HttpResponseMessage responseMessage = null;
string username = Thread.CurrentPrincipal.Identity.Name;
}
P20
<script type="text/javascript">
$(document).ready(function () {
var btnGetEmployee = $('#btnGetEmployee');
var btnClear = $('#btnClear');
var txtUserName = $('#txtUserName');
var txtPasswrod = $('#txtPasswrod');
$(document).ready(function () {
var btnGetEmployee = $('#btnGetEmployee');
var btnClear = $('#btnClear');
var txtUserName = $('#txtUserName');
var txtPasswrod = $('#txtPasswrod');
btnGetEmployee.click(function () {
$.ajax({
type: "GET",
url: "api/employee/",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
var result = "";
$.each(response, function (index, value) {
$.ajax({
type: "GET",
url: "api/employee/",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
var result = "";
$.each(response, function (index, value) {
var name = value.FirstName + " " + value.LastName;
result = result + "<div class='div-css'>" + name + "</div>";
});
result = result + "<div class='div-css'>" + name + "</div>";
});
$('#divUserDetails').html(result);
txtPasswrod.text('ajax call ');
},
error: function (response) {
alert('error occured');
}
});
txtPasswrod.text('ajax call ');
},
error: function (response) {
alert('error occured');
}
});
});
btnClear.click(function () { $('#divUserDetails').empty(); });
});
btnClear.click(function () { $('#divUserDetails').empty(); });
});
</script>



Comments
Post a Comment